<?php
/**
 * Plugin Name: WP Multi
 * Plugin URI: https://git.viper.ipv64.net/M_Viper/wp-multi
 * Description: Erweiterter Anti-Spam-Schutz mit Honeypot, Keyword-Filter, Link-Limit und mehr. Jetzt mit Statistik im Dashboard und HappyForms-Integration.
 * Version: 3.4
 * Author: M_Viper
 * Author URI: https://m-viper.de
 * Requires at least: 6.7.2
 * Tested up to: 6.7.2
 * PHP Version: 7.2
 * License: GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: wp-multi
 * Tags: anti-spam, security, honeypot, comment-protection, statistics, happyforms
 * Support: [Microsoft Teams Support](https://teams.live.com/l/community/FEAzokphpZTJ2u6OgI)
 * Support: [Telegram Support](https://t.me/M_Viper04)
 */

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


// Funktion zur Überprüfung des WP Multi Toolkit Plugins
function wp_multi_check_dependency() {
    if (!function_exists('is_plugin_active')) {
        include_once(ABSPATH . 'wp-admin/includes/plugin.php');
    }
    
    // Prüft, ob WP Multi Toolkit installiert und aktiv ist
    if (!is_plugin_active('wp-multi-toolkit/wp-multi-toolkit.php')) {
        add_action('admin_notices', 'wp_multi_dependency_notice');
        return false;
    }
    return true;
}

// Fehlermeldung für Admin-Bereich mit Download-Button
function wp_multi_dependency_notice() {
    ?>
    <div class="notice notice-error">
        <p>
            <?php _e('Das Plugin "WP Multi" benötigt "WP Multi Toolkit", um zu funktionieren. Bitte installieren und aktivieren Sie "WP Multi Toolkit".', 'wp-multi'); ?>
            <a href="https://git.viper.ipv64.net/M_Viper/wp-multi-toolkit/releases" target="_blank" class="button button-primary" style="margin-left: 10px;">
                <?php _e('WP Multi Toolkit herunterladen', 'wp-multi'); ?>
            </a>
        </p>
    </div>
    <?php
}

// Plugin nur initialisieren, wenn Abhängigkeit erfüllt ist
if (wp_multi_check_dependency()) {
    // Hier würde der restliche Plugin-Code folgen
    
} else {
    // Optional: Plugin komplett deaktivieren, wenn Abhängigkeit fehlt
    add_action('admin_init', function() {
        deactivate_plugins(plugin_basename(__FILE__));
    });
}


/*
 * Admin - Panel Banner
 */


 // Admin-Banner als Notice mit Blauem Hintergrund (#0073aa)
 function wp_multi_add_warning_banner() {
     // Verwende printf für bessere Lesbarkeit und Übersetzbarkeit
     printf(
         '<div class="notice notice-warning is-dismissible" style="background-color: #0073aa; color: white; border-left: 4px solid #005177;">
             <p><strong>%s</strong> %s <a href="%s" target="_blank" style="color: #FFDD00; text-decoration: none;">%s</a> %s</p>
             <p><strong>%s:</strong> %s <a href="%s" target="_blank" style="color: #FFDD00; text-decoration: none;">%s</a> %s <a href="%s" target="_blank" style="color: #FFDD00; text-decoration: none;">%s</a> %s</p>
         </div>',
         esc_html__('Danke, dass du WP Multi verwendest!', 'wp-multi'),
         esc_html__('Dein Feedback hilft uns, das Plugin ständig zu verbessern. Wenn du Fehler entdeckst oder Verbesserungsvorschläge hast, besuche bitte unsere', 'wp-multi'),
         'https://git.viper.ipv64.net/M_Viper/wp-multi',
         esc_html__('Gitea-Seite', 'wp-multi'),
         esc_html__('und teile uns deine Ideen mit!', 'wp-multi'),
         esc_html__('Support', 'wp-multi'),
         esc_html__('Bei Fragen oder Supportanfragen kannst du uns über', 'wp-multi'),
         'https://teams.live.com/l/community/FEAzokphpZTJ2u6OgI',
         esc_html__('Microsoft Teams', 'wp-multi'),
         esc_html__('oder', 'wp-multi'),
         'https://t.me/M_Viper04',
         esc_html__('Telegram', 'wp-multi'),
         esc_html__('erreichen.', 'wp-multi')
     );
 }
 add_action('admin_notices', 'wp_multi_add_warning_banner');
 
 // Support-Links in der Plugin-Übersicht anzeigen
 function wp_multi_plugin_row_meta($links, $file) {
     if ($file === plugin_basename(__FILE__)) {
         $new_links = array(
             'support_teams' => sprintf(
                 '<a href="%s" target="_blank" style="color: rgb(255, 0, 0);">%s</a>',
                 esc_url('https://teams.live.com/l/community/FEAzokphpZTJ2u6OgI'),
                 esc_html__('Microsoft Teams Support', 'wp-multi')
             ),
             'support_telegram' => sprintf(
                 '<a href="%s" target="_blank" style="color: rgb(255, 0, 0);">%s</a>',
                 esc_url('https://t.me/M_Viper04'),
                 esc_html__('Telegram Support', 'wp-multi')
             ),
         );
         $links = array_merge($links, $new_links);
     }
     return $links;
 }
 add_filter('plugin_row_meta', 'wp_multi_plugin_row_meta', 10, 2);
 

/*
* Index Verzeichnis [alphabetical_index]
*/


// Shortcode zum Erstellen des Indexes
function wp_multi_alphabetical_index($atts) {
    // Definiere die Argumente für den Shortcode
    $atts = shortcode_atts(array(
        'posts_per_page' => 20, // Maximale Beiträge pro Seite
    ), $atts, 'alphabetical_index');

    // Hole alle Beiträge
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC',
    );

    $posts = get_posts($args);

    // Beiträge nach Anfangsbuchstaben gruppieren
    $alphabet = range('A', 'Z');
    $posts_by_letter = array();

    foreach ($posts as $post) {
        $first_letter = strtoupper(substr($post->post_title, 0, 1));
        if (in_array($first_letter, $alphabet)) {
            $posts_by_letter[$first_letter][] = $post;
        }
    }

    // Holen des aktuellen Buchstabens aus der URL
    $letter = isset($_GET['letter']) ? strtoupper($_GET['letter']) : ''; // Der Buchstabe aus der URL

    // Bestimme, welche Beiträge angezeigt werden
    $posts_in_letter = [];
    if ($letter && isset($posts_by_letter[$letter])) {
        $posts_in_letter = $posts_by_letter[$letter];
    }

    // Teile die Beiträge in zwei Hälften für die Boxen
    $halfway = ceil(count($posts_in_letter) / 2); // Rundet die Hälfte auf
    $first_half = array_slice($posts_in_letter, 0, $halfway); // Erste Hälfte der Beiträge
    $second_half = array_slice($posts_in_letter, $halfway); // Zweite Hälfte der Beiträge

    // Ausgabe
    ob_start();
    ?>

    <div class="alphabetical-index">
        <!-- Links zu den Buchstaben -->
        <div class="alphabet-links">
            <?php foreach ($alphabet as $char): ?>
                <a href="?letter=<?php echo $char; ?>" class="letter-link"><?php echo $char; ?></a>
            <?php endforeach; ?>
        </div>

        <?php if ($letter): ?>
            <!-- Box für den aktuellen Buchstaben -->
            <div class="letter-heading-box">
                <h2>Beiträge für: <?php echo $letter; ?></h2>
            </div>

            <!-- Zeige die Beiträge für den ausgewählten Buchstaben in zwei Boxen -->
            <div class="letter-pair-container">
                <div class="letter-box">
                    <ul class="post-list">
                        <?php foreach ($first_half as $post): ?>
                            <li><a href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title; ?></a></li>
                        <?php endforeach; ?>
                    </ul>
                </div>

                <div class="letter-box">
                    <ul class="post-list">
                        <?php foreach ($second_half as $post): ?>
                            <li><a href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title; ?></a></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <style>
    .alphabetical-index {
        font-family: Arial, sans-serif;
        margin: 20px;
    }

    .alphabet-links {
        margin-bottom: 20px;
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
    }

    .alphabet-links a {
        margin-right: 10px;
        font-size: 18px;
        text-decoration: none;
        color: #0073aa;
    }

    .alphabet-links a:hover {
        text-decoration: underline;
    }

    .letter-heading-box {
        margin-bottom: 20px;
        background-color: #f0f0f0;
        padding: 20px;
        text-align: center;
        border-radius: 8px;
    }

    .letter-heading-box h2 {
        font-size: 24px;
        margin: 0;
    }

    .letter-pair-container {
        display: flex;
        gap: 30px;
        justify-content: space-between;
    }

    .letter-box {
        width: 48%;
        background-color: #f0f0f0;
        padding: 20px;
        border-radius: 8px;
    }

    .letter-box h2 {
        font-size: 24px;
        margin-bottom: 10px;
    }

    .post-list {
        list-style-type: none;
        padding: 0;
    }

    .post-list li {
        margin-bottom: 5px;
    }

    .post-list a {
        text-decoration: none;
        color: #333;
    }

    .post-list a:hover {
        text-decoration: underline;
    }
    </style>

    <?php
    return ob_get_clean();
}

// Shortcode registrieren
add_shortcode('alphabetical_index', 'wp_multi_alphabetical_index');


/*
* Sperre Trash Mail Adressen
*/


// Funktion zum Laden der Liste von Einweg-Mail-Anbietern
function load_disposable_email_list() {
    $file_path = plugin_dir_path(__FILE__) . 'includes/disposable_email_blocklist.conf'; // Pfad zur Datei im includes-Ordner
    if (file_exists($file_path)) {
        return file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    }
    return [];
}

// Funktion zum Überprüfen der E-Mail-Adresse eines Kommentators
function check_disposable_email($commentdata) {
    $disposable_list = load_disposable_email_list();
    $email = $commentdata['comment_author_email'];
    $domain = substr(strrchr($email, "@"), 1); // Nur die Domain extrahieren

    // Überprüfen, ob die Domain auf der Liste steht
    if (in_array($domain, $disposable_list)) {
        wp_die(__('Fehler: Trash-Mail-Adressen sind in Kommentaren nicht erlaubt.'));
    }

    return $commentdata;
}

// Die Funktion wird beim Absenden eines Kommentars ausgeführt
add_filter('preprocess_comment', 'check_disposable_email');




/*
* Text Copy Schutz und Schutz vor Entwicklertools
*/


// JavaScript für die Kopierschutz-Funktion einbinden
function wp_multi_enqueue_scripts() {
    wp_add_inline_script('jquery', "
        jQuery(document).ready(function($) {
            // Verhindert das Öffnen der Entwicklertools mit F12, Strg+Shift+I und Strg+Shift+C
            $(document).keydown(function(e) {
                // Blockiert F12, Strg + Shift + I, Strg + Shift + C (Entwicklertools)
                if (e.keyCode == 123 || (e.ctrlKey && e.shiftKey && e.keyCode == 73) || (e.ctrlKey && e.shiftKey && e.keyCode == 67)) {
                    e.preventDefault();
                }

                // Verhindert das Öffnen des Quellcodes mit Strg + U (view-source)
                if ((e.ctrlKey && e.keyCode == 85) || (e.ctrlKey && e.shiftKey && e.keyCode == 85)) {
                    e.preventDefault();
                }

                // Verhindert den Zugriff auf die Konsole mit Strg + Shift + J (Konsole-Tab)
                if ((e.ctrlKey && e.shiftKey && e.keyCode == 74) || (e.metaKey && e.altKey && e.keyCode == 74)) {
                    e.preventDefault();
                }

                // Verhindert das Öffnen des Quellcodes mit view-source
                if (e.ctrlKey && e.keyCode == 85) {
                    e.preventDefault();
                }
            });

            // Verhindert das Öffnen des Kontextmenüs (Rechtsklick)
            $('body').on('contextmenu', function(e) {
                e.preventDefault();
            });

            // Kopierschutz-Funktion
            $('body').on('copy', function(e) {
                e.preventDefault();
                var selectedText = window.getSelection().toString();
                var numericText = selectedText.replace(/./g, function(char) {
                    return Math.floor(Math.random() * 10);
                });
                
                e.originalEvent.clipboardData.setData('text/plain', numericText);
            });
        });
    ");
}
add_action('wp_enqueue_scripts', 'wp_multi_enqueue_scripts');


/*
* Login deaktivieren
*/


// Checkbox zum Benutzerprofil hinzufügen
function wp_multi_add_disable_login_checkbox($user) {
    ?>
    <h3>Login deaktivieren</h3>
    <table class="form-table">
        <tr>
            <th><label for="disable_login">Login deaktivieren</label></th>
            <td>
                <input type="checkbox" name="disable_login" id="disable_login" value="1" <?php checked( get_user_meta($user->ID, 'disable_login', true), 1 ); ?> />
                <span class="description">Markiere diese Option, um den Login des Benutzers zu deaktivieren.</span>
            </td>
        </tr>
    </table>
    <?php
}

// Speichern der Checkbox-Option
function wp_multi_save_disable_login_checkbox($user_id) {
    if ( isset( $_POST['disable_login'] ) ) {
        update_user_meta( $user_id, 'disable_login', 1 );
    } else {
        delete_user_meta( $user_id, 'disable_login' );
    }
}

// Die Checkbox in das Benutzerprofil einfügen
add_action( 'show_user_profile', 'wp_multi_add_disable_login_checkbox' );
add_action( 'edit_user_profile', 'wp_multi_add_disable_login_checkbox' );

// Speichern der Checkbox-Option
add_action( 'personal_options_update', 'wp_multi_save_disable_login_checkbox' );
add_action( 'edit_user_profile_update', 'wp_multi_save_disable_login_checkbox' );

// Login blockieren, wenn die Checkbox aktiviert ist
function wp_multi_block_login_if_disabled($user_login, $user) {
    // Prüfen, ob der Benutzer das Flag "Login deaktivieren" gesetzt hat
    if ( get_user_meta( $user->ID, 'disable_login', true ) ) {
        // Fehlermeldung anzeigen, wenn der Login deaktiviert ist
        wp_die( 'Dein Login wurde deaktiviert. Bitte kontaktiere den Administrator.' );
    }
}

// Der Filter wird bei jedem Login-Versuch angewendet
add_action( 'wp_login', 'wp_multi_block_login_if_disabled', 10, 2 );
 
 
/*
 * Verbessertes Auto-Tag-Plugin mit optimierter Sicherheit, Performance und Benutzerfreundlichkeit
 */

define('WP_MULTI_AUTO_TAGS_OPTION', 'wp_multi_custom_stopwords');
define('WP_MULTI_AUTO_TAGS_QUEUE', 'wp_multi_auto_tags_queue');
define('WP_MULTI_AUTO_TAGS_NONCE', 'wp_multi_auto_tags_nonce');

/**
 * Fügt automatische Tags zu einem Beitrag hinzu.
 *
 * @param int $post_id ID des Beitrags.
 */
function wp_multi_auto_add_tags($post_id) {
    if (get_post_type($post_id) !== 'post') {
        return;
    }

    $existing_tags = wp_get_post_tags($post_id, ['fields' => 'names']);
    if (!empty($existing_tags)) {
        return;
    }

    $post = get_post($post_id);
    if (!$post) {
        error_log("WP Multi Auto Tags: Beitrag $post_id nicht gefunden.");
        return;
    }

    $content = strip_tags($post->post_content);
    $content = mb_strtolower($content, 'UTF-8');

    // Stopwörter laden
    $stopwords = wp_multi_get_stopwords();
    $words = wp_multi_extract_words($content, $stopwords);

    if (empty($words)) {
        return;
    }

    $word_counts = array_count_values($words);
    arsort($word_counts);

    $top_tags = array_slice(array_keys($word_counts), 0, 5);
    if (!empty($top_tags)) {
        wp_set_post_tags($post_id, $top_tags, true);
    }
}

/**
 * Extrahiert relevante Wörter aus dem Inhalt.
 *
 * @param string $content Der Inhalt des Beitrags.
 * @param array  $stopwords Liste der Stopwörter.
 * @return array Liste der extrahierten Wörter.
 */
function wp_multi_extract_words($content, $stopwords) {
    preg_match_all('/\b[a-zäöüß]{4,}\b/u', $content, $matches);
    return array_unique(array_diff($matches[0], $stopwords));
}

/**
 * Lädt die kombinierten Stopwörter (Standard + benutzerdefiniert).
 *
 * @return array Liste der Stopwörter.
 */
function wp_multi_get_stopwords() {
    $cache_key = 'wp_multi_stopwords';
    $stopwords = get_transient($cache_key);

    if ($stopwords !== false) {
        return $stopwords;
    }

    $custom_stopwords = get_option(WP_MULTI_AUTO_TAGS_OPTION, '');
    $custom_stopwords = array_filter(array_map('trim', explode(',', sanitize_text_field($custom_stopwords))));

    $default_stopwords = [
        'und', 'oder', 'ein', 'eine', 'der', 'die', 'das', 'in', 'mit', 'auf', 'zu', 'von',
        'für', 'ist', 'es', 'im', 'an', 'am', 'bei', 'auch', 'aber', 'so', 'dass', 'kann',
        'wenn', 'wie', 'wir', 'man', 'nur', 'nicht', 'mehr', 'als', 'sein', 'wurde', 'werden',
        'hat', 'haben', 'schon', 'doch', 'denn', 'diese', 'dieser', 'dieses', 'nach', 'sehr', 'allgemein'
    ];

    $stopwords = array_merge($default_stopwords, $custom_stopwords);
    set_transient($cache_key, $stopwords, DAY_IN_SECONDS);
    return $stopwords;
}

/**
 * Fügt das Admin-Menü für automatische Tags hinzu.
 */
function wp_multi_admin_menu() {
    add_submenu_page(
        'edit.php',
        __('Automatische Tags', 'wp-multi'),
        __('Automatische Tags', 'wp-multi'),
        'manage_options',
        'wp-multi-auto-tags',
        'wp_multi_auto_tags_page'
    );
}
add_action('admin_menu', 'wp_multi_admin_menu');

/**
 * Rendert die Admin-Seite für automatische Tags.
 */
function wp_multi_auto_tags_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('Zugriff verweigert.', 'wp-multi'));
    }

    ?>
    <div class="wrap">
        <div class="wp-multi-header">
            <img src="https://m-viper.de/img/logo.png" alt="M_Viper Logo">
            <h1><?php esc_html_e('Automatische Tags', 'wp-multi'); ?></h1>
        </div>

        <p class="wp-multi-description"><?php esc_html_e('Automatisch Tags zu Beiträgen hinzufügen, die noch keine haben.', 'wp-multi'); ?></p>

        <form method="post" action="options.php">
            <?php
            settings_fields('wp_multi_auto_tags_options');
            do_settings_sections('wp-multi-auto-tags');
            wp_nonce_field(WP_MULTI_AUTO_TAGS_NONCE, WP_MULTI_AUTO_TAGS_NONCE);
            ?>
            <p>
                <label for="wp_multi_custom_stopwords"><?php esc_html_e('Benutzerdefinierte Stopwörter (kommagetrennt):', 'wp-multi'); ?></label><br>
                <textarea id="wp_multi_custom_stopwords" name="wp_multi_custom_stopwords" rows="5" cols="50"><?php echo esc_textarea(get_option(WP_MULTI_AUTO_TAGS_OPTION, '')); ?></textarea>
                <br>
                <small><?php esc_html_e('Beispiele: wird, auch, aber', 'wp-multi'); ?></small>
            </p>
            <p><input type="submit" value="<?php esc_html_e('Speichern', 'wp-multi'); ?>" class="button button-primary"></p>
        </form>

        <button id="start-auto-tags" class="button button-primary wp-multi-btn"><?php esc_html_e('Jetzt ausführen', 'wp-multi'); ?></button>
        <div id="progress-container" class="wp-multi-progress-container">
            <div id="progress-bar" class="wp-multi-progress-bar">0%</div>
        </div>
        <p id="status-message" class="wp-multi-status-message"></p>
    </div>

    <?php
    wp_enqueue_style('wp-multi-auto-tags', plugin_dir_url(__FILE__) . 'css/auto-tags.css', [], '1.1');
    wp_add_inline_style('wp-multi-auto-tags', '
        .wp-multi-header { background: #0073aa; color: white; text-align: center; padding: 25px; border-radius: 8px; margin-bottom: 30px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); }
        .wp-multi-header img { max-width: 120px; margin-bottom: 15px; }
        .wp-multi-header h1 { font-size: 24px; font-weight: 600; margin: 0; }
        .wp-multi-description { font-size: 18px; margin-bottom: 25px; color: #555; }
        .wp-multi-btn { background: #0073aa; color: white; border: none; padding: 12px 24px; font-size: 18px; cursor: pointer; border-radius: 5px; transition: background 0.3s ease, transform 0.3s ease; }
        .wp-multi-btn:hover { background: #005f8a; transform: translateY(-2px); }
        .wp-multi-btn:disabled { background: #cccccc; cursor: not-allowed; transform: none; }
        textarea { width: 100%; padding: 12px; border-radius: 5px; border: 1px solid #ddd; font-size: 16px; line-height: 1.5; box-sizing: border-box; }
        label { font-size: 16px; font-weight: 500; color: #333; margin-bottom: 8px; display: block; }
        small { font-size: 14px; color: #888; }
        .wp-multi-progress-container { display: none; width: 100%; background: #f4f4f4; border-radius: 5px; margin-top: 20px; }
        .wp-multi-progress-bar { width: 0%; height: 30px; background: #2da807; text-align: center; color: white; line-height: 30px; font-weight: bold; transition: width 0.4s ease-in-out; border-radius: 5px; }
        .wp-multi-status-message { margin-top: 15px; font-size: 16px; font-weight: bold; color: #0073aa; }
        form { margin-bottom: 25px; background: #f9f9f9; padding: 20px; border-radius: 8px; box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05); }
    ');

    wp_enqueue_script('wp-multi-auto-tags', plugin_dir_url(__FILE__) . 'js/auto-tags.js', ['jquery'], '1.1', true);
    wp_localize_script('wp-multi-auto-tags', 'wpMultiAutoTags', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce(WP_MULTI_AUTO_TAGS_NONCE),
        'messages' => [
            'processing' => __('Wird verarbeitet...', 'wp-multi'),
            'run' => __('Jetzt ausführen', 'wp-multi'),
            'loading' => __('Lade...', 'wp-multi'),
            'no_posts' => __('Keine Beiträge gefunden.', 'wp-multi'),
            'success' => __('Automatische Tags erfolgreich hinzugefügt!', 'wp-multi'),
            'error' => __('Fehler bei der Verarbeitung.', 'wp-multi'),
            'start_error' => __('Fehler beim Starten der Verarbeitung.', 'wp-multi'),
        ],
    ]);
    ?>
    <script>
        jQuery(document).ready(function($) {
            $('#start-auto-tags').on('click', function() {
                const button = $(this);
                const progressContainer = $('#progress-container');
                const progressBar = $('#progress-bar');
                const statusMessage = $('#status-message');

                button.prop('disabled', true).text(wpMultiAutoTags.messages.processing);
                progressContainer.show();
                progressBar.css('width', '0%').text('0%');
                statusMessage.text(wpMultiAutoTags.messages.loading);

                $.ajax({
                    url: wpMultiAutoTags.ajaxurl,
                    method: 'POST',
                    data: {
                        action: 'wp_multi_process_auto_tags',
                        nonce: wpMultiAutoTags.nonce,
                    },
                    success: function(response) {
                        if (!response.data.total) {
                            statusMessage.text(wpMultiAutoTags.messages.no_posts);
                            button.prop('disabled', false).text(wpMultiAutoTags.messages.run);
                            return;
                        }

                        const total = response.data.total;
                        let processed = 0;
                        const batchSize = 10;

                        function processBatch() {
                            $.ajax({
                                url: wpMultiAutoTags.ajaxurl,
                                method: 'POST',
                                data: {
                                    action: 'wp_multi_process_auto_tags_step',
                                    batchSize: batchSize,
                                    nonce: wpMultiAutoTags.nonce,
                                },
                                success: function(result) {
                                    if (result.data.done) {
                                        processed += batchSize;
                                        const percent = Math.min(Math.round((processed / total) * 100), 100);
                                        progressBar.css('width', percent + '%').text(percent + '%');

                                        if (processed < total) {
                                            processBatch();
                                        } else {
                                            button.prop('disabled', false).text(wpMultiAutoTags.messages.run);
                                            statusMessage.text(wpMultiAutoTags.messages.success);
                                        }
                                    }
                                },
                                error: function() {
                                    statusMessage.text(wpMultiAutoTags.messages.error);
                                    button.prop('disabled', false).text(wpMultiAutoTags.messages.run);
                                },
                            });
                        }
                        processBatch();
                    },
                    error: function() {
                        statusMessage.text(wpMultiAutoTags.messages.start_error);
                        button.prop('disabled', false).text(wpMultiAutoTags.messages.run);
                    },
                });
            });
        });
    </script>
    <?php
}

/**
 * Registriert die Einstellungen für automatische Tags.
 */
function wp_multi_auto_tags_settings_init() {
    register_setting('wp_multi_auto_tags_options', WP_MULTI_AUTO_TAGS_OPTION, [
        'sanitize_callback' => function($input) {
            $input = sanitize_text_field($input);
            return implode(',', array_map('trim', explode(',', $input)));
        },
    ]);
}
add_action('admin_init', 'wp_multi_auto_tags_settings_init');

/**
 * Verarbeitet die Initialisierung der Auto-Tag-Verarbeitung via AJAX.
 */
function wp_multi_process_auto_tags() {
    check_ajax_referer(WP_MULTI_AUTO_TAGS_NONCE, 'nonce');

    $args = [
        'post_type' => 'post',
        'posts_per_page' => 100,
        'fields' => 'ids',
        'no_found_rows' => true, // Optimierung
    ];

    $posts = get_posts($args);
    if (empty($posts)) {
        wp_send_json_success(['total' => 0]);
    }

    set_transient(WP_MULTI_AUTO_TAGS_QUEUE, $posts, 300);
    wp_send_json_success(['total' => count($posts)]);
}
add_action('wp_ajax_wp_multi_process_auto_tags', 'wp_multi_process_auto_tags');

/**
 * Verarbeitet einen Batch von Beiträgen für die Auto-Tag-Verarbeitung.
 */
function wp_multi_process_auto_tags_step() {
    check_ajax_referer(WP_MULTI_AUTO_TAGS_NONCE, 'nonce');

    $queue = get_transient(WP_MULTI_AUTO_TAGS_QUEUE);
    $batchSize = isset($_POST['batchSize']) ? absint($_POST['batchSize']) : 10;
    $batchSize = max(1, min($batchSize, 50));

    if (!$queue || empty($queue)) {
        wp_send_json_success(['done' => false]);
    }

    set_time_limit(30); // Timeout verhindern
    $posts_to_process = array_splice($queue, 0, $batchSize);

    foreach ($posts_to_process as $post_id) {
        wp_multi_auto_add_tags($post_id);
    }

    set_transient(WP_MULTI_AUTO_TAGS_QUEUE, $queue, 300);
    wp_send_json_success(['done' => true]);
}
add_action('wp_ajax_wp_multi_process_auto_tags_step', 'wp_multi_process_auto_tags_step');

/**
 * Fügt Tags automatisch bei neuen oder aktualisierten Beiträgen hinzu.
 *
 * @param int $post_id ID des Beitrags.
 */
function wp_multi_auto_tag_on_save($post_id) {
    if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
        return;
    }

    wp_multi_auto_add_tags($post_id);
}
add_action('save_post', 'wp_multi_auto_tag_on_save', 10, 1);



/*
* Anti Spam Honey 
*/


// Standardwerte setzen
function wp_multi_set_default_options() {
    add_option('wp_multi_honeypot_field', 'iwlxja5187');
    add_option('wp_multi_honeypot_error', 'Spamming or your Javascript is disabled !!');
    add_option('wp_multi_honeypot_widget', 0);
    add_option('wp_multi_max_links', 3);
    add_option('wp_multi_blocked_keywords', 'viagra,casino,bitcoin');
    add_option('wp_multi_blocked_ips', '');
    add_option('wp_multi_blocked_comments', 0); // Zähler für blockierte Kommentare
    add_option('wp_multi_honeypot_hits', 0); // Zähler für Honeypot-Aktivierungen
    add_option('wp_multi_spammer_ips', []); // Liste der blockierten Spammer-IP-Adressen
    add_option('wp_multi_spam_submissions', []); // Liste der Spam-Einreichungen
}
register_activation_hook(__FILE__, 'wp_multi_set_default_options');

// Menüpunkt "Sicherheit" und Statistik hinzufügen
function wp_multi_add_security_menu() {
    add_menu_page(
        'Sicherheit', 
        'Sicherheit', 
        'manage_options', 
        'wp-multi-security', 
        'wp_multi_security_settings_page', 
        'dashicons-shield', 
        80
    );
    add_submenu_page(
        'wp-multi-security', 
        'WP Multi Statistik', 
        'WP Multi Statistik', 
        'manage_options', 
        'wp-multi-statistics', 
        'wp_multi_statistics_page'
    );
}
add_action('admin_menu', 'wp_multi_add_security_menu');

// Einstellungsseite mit CSS & JS für Generator
function wp_multi_security_settings_page() {
    ?>
    <div class="wp-multi-security-wrap">
        <div class="wp-multi-banner">
            <img src="https://m-viper.de/img/logo.png" alt="WP Multi Logo">
            <h1>WP Multi - Anti Spam</h1>
        </div>
        <form method="post" action="options.php">
            <?php
            settings_fields('wp_multi_security_settings');
            do_settings_sections('wp-multi-security');
            submit_button();
            ?>
        </form>
    </div>
    <script>
        function generateHoneypotName() {
            let field = document.getElementById('wp_multi_honeypot_field');
            let randomString = Math.random().toString(36).substring(2, 12);
            field.value = randomString;
        }
    </script>
    <style>
        .wp-multi-security-wrap {
            max-width: 700px;
            margin: 20px auto;
            padding: 20px;
            background: #f9f9f9;
            border-radius: 10px;
            box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
        }
        .wp-multi-banner {
            background: #0073aa;
            padding: 15px;
            text-align: center;
            border-radius: 10px;
            color: #fff;
        }
        .wp-multi-banner img {
            max-height: 50px;
            display: block;
            margin: 0 auto 10px;
        }
        .wp-multi-banner h1 {
            margin: 0;
            font-size: 22px;
        }
        .wp-multi-honeypot-group {
            display: flex;
            align-items: center;
        }
        .wp-multi-honeypot-group input {
            flex: 1;
            margin-right: 10px;
        }
        button {
            cursor: pointer;
            background: #0073aa;
            color: #fff;
            border: none;
            padding: 5px 10px;
            border-radius: 5px;
        }
        button:hover {
            background: #005f88;
        }
    </style>
    <?php
}

// Statistikseite im Dashboard
function wp_multi_statistics_page() {
    $blocked_comments = get_option('wp_multi_blocked_comments', 0);
    $honeypot_hits = get_option('wp_multi_honeypot_hits', 0);
    $spammer_ips = get_option('wp_multi_spammer_ips', []);
    $spam_submissions = get_option('wp_multi_spam_submissions', []);
    
    ?>
    <div class="wrap wp-multi-statistics-wrap">
        <div class="wp-multi-banner">
            <img src="https://m-viper.de/img/logo.png" alt="WP Multi Logo">
            <h1>WP Multi - Anti Spam Statistik</h1>
        </div>

        <div class="wp-multi-statistics">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>Statistik</th>
                        <th>Wert</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Blockierte Kommentare</td>
                        <td><?php echo $blocked_comments; ?></td>
                    </tr>
                    <tr>
                        <td>Aktivierte Honeypot-Felder</td>
                        <td><?php echo $honeypot_hits; ?></td>
                    </tr>
                    <tr>
                        <td>Spammer-IP-Adressen</td>
                        <td><?php echo count($spammer_ips); ?></td>
                    </tr>
                    <tr>
                        <td>Spam-Einreichungen</td>
                        <td><?php echo count($spam_submissions); ?></td>
                    </tr>
                </tbody>
            </table>

            <h2>Spammer-IP-Adressen</h2>
            <?php if (!empty($spammer_ips)): ?>
                <ul class="wp-multi-spammer-ips">
                    <?php foreach ($spammer_ips as $ip): ?>
                        <li><?php echo esc_html($ip); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <p>Keine Spammer-IP-Adressen gefunden.</p>
            <?php endif; ?>
        </div>
    </div>

    <style>
        .wp-multi-statistics-wrap {
            max-width: 900px;
            margin: 20px auto;
            padding: 20px;
            background: #f9f9f9;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .wp-multi-banner {
            background: #0073aa;
            padding: 20px;
            text-align: center;
            border-radius: 10px;
            color: #fff;
        }

        .wp-multi-banner img {
            max-height: 60px;
            display: block;
            margin: 0 auto 10px;
        }

        .wp-multi-banner h1 {
            margin: 0;
            font-size: 24px;
            font-weight: bold;
        }

        .wp-multi-statistics table {
            width: 100%;
            margin-top: 20px;
            border-collapse: collapse;
        }

        .wp-multi-statistics th,
        .wp-multi-statistics td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        .wp-multi-statistics th {
            background-color: #0073aa;
            color: #fff;
        }

        .wp-multi-statistics tbody tr:hover {
            background-color: #f1f1f1;
        }

        .wp-multi-spammer-ips {
            list-style-type: none;
            padding-left: 0;
        }

        .wp-multi-spammer-ips li {
            padding: 5px;
            background-color: #f1f1f1;
            margin: 5px 0;
            border-radius: 5px;
        }
    </style>
    <?php
}


// Einstellungen registrieren
function wp_multi_register_security_settings() {
    register_setting('wp_multi_security_settings', 'wp_multi_honeypot_field');
    register_setting('wp_multi_security_settings', 'wp_multi_honeypot_error');
    register_setting('wp_multi_security_settings', 'wp_multi_honeypot_widget');
    register_setting('wp_multi_security_settings', 'wp_multi_max_links');
    register_setting('wp_multi_security_settings', 'wp_multi_blocked_keywords');
    register_setting('wp_multi_security_settings', 'wp_multi_blocked_ips');

    add_settings_section('wp_multi_honeypot_section', 'Honeypot Einstellungen', null, 'wp-multi-security');

    add_settings_field('wp_multi_honeypot_field', 'Honey Pot Field Name', 'wp_multi_honeypot_field_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_honeypot_error', 'Honey Pot Error Message', 'wp_multi_honeypot_error_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_honeypot_widget', 'Disable Honeypot Test Widget', 'wp_multi_honeypot_widget_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_max_links', 'Maximale Links im Kommentar', 'wp_multi_max_links_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_blocked_keywords', 'Blockierte Schlüsselwörter', 'wp_multi_blocked_keywords_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
    add_settings_field('wp_multi_blocked_ips', 'Blockierte IP-Adressen', 'wp_multi_blocked_ips_callback', 'wp-multi-security', 'wp_multi_honeypot_section');
}

add_action('admin_init', 'wp_multi_register_security_settings');

function wp_multi_honeypot_field_callback() {
    ?>
    <div class="wp-multi-honeypot-group">
        <input type="text" id="wp_multi_honeypot_field" name="wp_multi_honeypot_field" value="<?php echo esc_attr(get_option('wp_multi_honeypot_field')); ?>">
        <button type="button" onclick="generateHoneypotName()">Generieren</button>
    </div>
    <small>Verwenden Sie ein zufälliges Zeichenfolgen für das Honeypot-Feld.</small>
    <?php
}

function wp_multi_honeypot_error_callback() {
    ?>
    <input type="text" name="wp_multi_honeypot_error" value="<?php echo esc_attr(get_option('wp_multi_honeypot_error')); ?>">
    <small>Die Nachricht, die angezeigt wird, wenn ein Honeypot ausgelöst wird.</small>
    <?php
}

function wp_multi_honeypot_widget_callback() {
    ?>
    <input type="checkbox" name="wp_multi_honeypot_widget" value="1" <?php checked(1, get_option('wp_multi_honeypot_widget'), true); ?>>
    <small>Deaktivieren Sie das Honeypot-Test-Widget im Frontend.</small>
    <?php
}

function wp_multi_max_links_callback() {
    ?>
    <input type="number" name="wp_multi_max_links" value="<?php echo esc_attr(get_option('wp_multi_max_links')); ?>">
    <small>Maximale Anzahl von Links, die in einem Kommentar erlaubt sind.</small>
    <?php
}

function wp_multi_blocked_keywords_callback() {
    ?>
    <input type="text" name="wp_multi_blocked_keywords" value="<?php echo esc_attr(get_option('wp_multi_blocked_keywords')); ?>">
    <small>Schlüsselwörter, die blockiert werden sollen (durch Kommas getrennt).</small>
    <?php
}

function wp_multi_blocked_ips_callback() {
    ?>
    <textarea name="wp_multi_blocked_ips" rows="5"><?php echo esc_textarea(get_option('wp_multi_blocked_ips')); ?></textarea>
    <small>Blockierte IP-Adressen (jede Adresse in einer neuen Zeile).</small>
    <?php
}


/*
* Schutz vor Brute-Force-Angriffen mit wöchentlicher Zusammenfassung
*/


// Funktion zur Erfassung der echten IP-Adresse des Benutzers
function get_user_ip() {
    if (!empty($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ips[0]);
        return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : $_SERVER['REMOTE_ADDR'];
    }
    return filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
}

// Funktion zur Verfolgung von fehlgeschlagenen Anmeldeversuchen
function wp_multi_log_failed_login($username) {
    global $wpdb;

    $ip = get_user_ip();
    if ($ip === '0.0.0.0') {
        return;
    }

    $table_name = $wpdb->prefix . 'blocked_ips';
    $user = get_user_by('login', $username);
    $max_attempts = 3;
    $block_threshold = 5;

    $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ip = %s", $ip));

    if ($row) {
        $wpdb->update(
            $table_name,
            array(
                'attempts' => $row->attempts + 1,
                'last_attempt' => current_time('mysql'),
            ),
            array('ip' => $ip),
            array('%d', '%s'),
            array('%s')
        );
        $attempts = $row->attempts + 1;
    } else {
        $wpdb->insert(
            $table_name,
            array(
                'ip' => $ip,
                'attempts' => 1,
                'last_attempt' => current_time('mysql'),
            ),
            array('%s', '%d', '%s')
        );
        $attempts = 1;
    }

    if ($attempts >= $block_threshold) {
        $email_sent = (int) get_option('failed_login_email_sent_' . $ip, 0);

        if ($email_sent < $max_attempts) {
            if ($user) {
                wp_mail(
                    $user->user_email,
                    __('Deine IP-Adresse wurde gesperrt', 'wp-multi'),
                    sprintf(
                        __("Hallo %s,\n\nDeine IP-Adresse wurde aufgrund zu vieler fehlgeschlagener Anmeldeversuche gesperrt. Bitte kontaktiere den Administrator.", 'wp-multi'),
                        $user->user_login
                    ),
                    array('Content-Type: text/plain; charset=UTF-8')
                );
            }
            update_option('failed_login_email_sent_' . $ip, $email_sent + 1);
        }

        wp_die(
            __('Deine IP-Adresse wurde aufgrund zu vieler Fehlversuche gesperrt. Bitte versuche es später noch einmal.', 'wp-multi'),
            __('Zugriff gesperrt', 'wp-multi'),
            array('response' => 403)
        );
    }
}

// Hook für fehlgeschlagene Anmeldungen
add_action('wp_login_failed', 'wp_multi_log_failed_login', 10, 1);

// Funktion zur Erstellung der Tabelle für blockierte IPs
function wp_multi_create_blocked_ips_table() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'blocked_ips';
    $charset_collate = $wpdb->get_charset_collate();
    $version = get_option('wp_multi_blocked_ips_version', '1.0');

    if (version_compare($version, '1.1', '<')) {
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            ip varchar(45) NOT NULL,
            attempts int NOT NULL DEFAULT 0,
            last_attempt datetime NOT NULL,
            PRIMARY KEY (id),
            KEY ip (ip)
        ) $charset_collate;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
        update_option('wp_multi_blocked_ips_version', '1.1');
    }
}
register_activation_hook(__FILE__, 'wp_multi_create_blocked_ips_table');

// Wöchentliche Zusammenfassung
function wp_multi_send_weekly_summary() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'blocked_ips';
    
    $last_email_time = get_option('wp_multi_last_summary_email', 0);
    $current_time = time();
    
    // Prüfen, ob eine Woche vergangen ist (7 Tage = 604800 Sekunden)
    if (($current_time - $last_email_time) < 604800) {
        return;
    }

    // Zeitraum für die Zusammenfassung (letzte Woche)
    $week_ago = date('Y-m-d H:i:s', strtotime('-7 days'));
    $now = date('Y-m-d H:i:s');
    
    // Gesamtzahl der Angriffe
    $total_attacks = $wpdb->get_var(
        $wpdb->prepare(
            "SELECT SUM(attempts) FROM $table_name WHERE last_attempt >= %s",
            $week_ago
        )
    );
    $total_attacks = $total_attacks ? $total_attacks : 0;

    // Top 10 IPs mit den meisten Angriffen
    $top_ips = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT ip, attempts, last_attempt 
             FROM $table_name 
             WHERE last_attempt >= %s 
             ORDER BY attempts DESC 
             LIMIT 10",
            $week_ago
        )
    );

    // E-Mail-Inhalt
    $message = __("Wöchentliche Brute-Force-Zusammenfassung\n\n", 'wp-multi');
    $message .= sprintf(__("Zeitraum: %s bis %s\n\n", 'wp-multi'), $week_ago, $now);
    $message .= sprintf(__("Gesamtzahl der Angriffe: %d\n\n", 'wp-multi'), $total_attacks);
    $message .= __("Top 10 IPs mit den meisten Angriffen:\n", 'wp-multi');
    
    if ($top_ips) {
        foreach ($top_ips as $index => $ip) {
            $message .= sprintf(
                __("%d. IP: %s, Versuche: %d, Letzter Versuch: %s\n", 'wp-multi'),
                $index + 1,
                $ip->ip,
                $ip->attempts,
                $ip->last_attempt
            );
        }
    } else {
        $message .= __("Keine IPs mit Angriffen in diesem Zeitraum.\n", 'wp-multi');
    }

    // E-Mail an Admin senden
    $admin_email = get_option('admin_email');
    wp_mail(
        $admin_email,
        __('Wöchentliche Brute-Force-Zusammenfassung', 'wp-multi'),
        $message,
        array('Content-Type: text/plain; charset=UTF-8')
    );

    // Aktualisiere den Zeitstempel der letzten E-Mail
    update_option('wp_multi_last_summary_email', $current_time);
}

// Planen der wöchentlichen Zusammenfassung (jeden Montag um 8:00 Uhr)
function wp_multi_schedule_weekly_summary() {
    if (!wp_next_scheduled('wp_multi_weekly_summary_event')) {
        wp_schedule_event(strtotime('next Monday 08:00'), 'weekly', 'wp_multi_weekly_summary_event');
    }
}
add_action('wp', 'wp_multi_schedule_weekly_summary');

// Hook für die Ausführung der Zusammenfassung
add_action('wp_multi_weekly_summary_event', 'wp_multi_send_weekly_summary');

// Menüpunkt für blockierte IPs
function wp_multi_blocked_ips_menu() {
    add_submenu_page(
        'wp-multi-security',
        __('Blockierte IPs', 'wp-multi'),
        __('Blockierte IPs', 'wp-multi'),
        'manage_options',
        'wp_multi_blocked_ips',
        'wp_multi_display_blocked_ips'
    );
}
add_action('admin_menu', 'wp_multi_blocked_ips_menu');

// Anzeige der blockierten IPs im Admin-Bereich
function wp_multi_display_blocked_ips() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'blocked_ips';

    $five_days_ago = date('Y-m-d H:i:s', strtotime('-5 days'));
    $per_page = 50;
    $page = max(1, isset($_GET['paged']) ? intval($_GET['paged']) : 1);
    $offset = ($page - 1) * $per_page;

    $blocked_ips = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM $table_name WHERE last_attempt >= %s ORDER BY last_attempt DESC LIMIT %d OFFSET %d",
            $five_days_ago,
            $per_page,
            $offset
        )
    );

    $total_ips = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_name WHERE last_attempt >= %s", $five_days_ago));
    $total_pages = ceil($total_ips / $per_page);

    ?>
    <div class="wrap">
        <h1><?php _e('Blockierte IPs (letzte 5 Tage)', 'wp-multi'); ?></h1>
        <?php if (empty($blocked_ips)) : ?>
            <p><?php _e('Keine blockierten IPs gefunden.', 'wp-multi'); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th><?php _e('ID', 'wp-multi'); ?></th>
                        <th><?php _e('IP-Adresse', 'wp-multi'); ?></th>
                        <th><?php _e('Versuche', 'wp-multi'); ?></th>
                        <th><?php _e('Letzter Versuch', 'wp-multi'); ?></th>
                        <th><?php _e('Aktionen', 'wp-multi'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($blocked_ips as $ip) : ?>
                        <tr>
                            <td><?php echo esc_html($ip->id); ?></td>
                            <td><?php echo esc_html($ip->ip); ?></td>
                            <td><?php echo esc_html($ip->attempts); ?></td>
                            <td><?php echo esc_html($ip->last_attempt); ?></td>
                            <td>
                                <a href="<?php echo esc_url(admin_url('admin-post.php?action=remove_blocked_ip&id=' . $ip->id)); ?>">
                                    <?php _e('Entfernen', 'wp-multi'); ?>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($total_pages > 1) : ?>
                <div class="tablenav">
                    <div class="tablenav-pages">
                        <?php
                        echo paginate_links(array(
                            'base' => add_query_arg('paged', '%#%'),
                            'format' => '',
                            'prev_text' => __('«'),
                            'next_text' => __('»'),
                            'total' => $total_pages,
                            'current' => $page,
                        ));
                        ?>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>

        <?php
        $three_days_ago = date('Y-m-d H:i:s', strtotime('-3 days'));
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM $table_name WHERE attempts < 10 AND last_attempt < %s",
                $three_days_ago
            )
        );
        ?>
    </div>
    <?php
}

// Funktion zum Entfernen einer blockierten IP
function wp_multi_remove_blocked_ip() {
    if (!current_user_can('manage_options')) {
        wp_die(__('Du hast nicht die erforderlichen Berechtigungen.', 'wp-multi'), '', array('response' => 403));
    }

    global $wpdb;
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    if ($id > 0) {
        $table_name = $wpdb->prefix . 'blocked_ips';
        $wpdb->delete($table_name, array('id' => $id), array('%d'));
    }

    wp_safe_redirect(admin_url('admin.php?page=wp_multi_blocked_ips'));
    exit;
}
add_action('admin_post_remove_blocked_ip', 'wp_multi_remove_blocked_ip');


/*
* Admin - Pinnwand
*/


// Funktion zum Erstellen der Datenbanktabelle für Nachrichten
function wp_multi_create_message_board_table() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'message_board'; // Tabelle für Nachrichten
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        message text NOT NULL,
        user_id bigint(20) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'wp_multi_create_message_board_table');

// Funktion zum Anzeigen der Nachrichten im Adminbereich
function wp_multi_add_message_board() {
    if (!current_user_can('administrator')) {
        return;
    }

    ?>
    <style>
        body {
            background-image: url('<?php echo plugin_dir_url( __FILE__ ); ?>img/pinwand.jpg');
            background-size: cover; 
            background-position: center; 
            background-repeat: no-repeat; 
            margin: 0;
            padding: 0;
            height: 100vh; 
            background-attachment: fixed; 
        }

        .message-board {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            padding: 20px;
            height: 100%; 
            overflow-y: auto; 
            z-index: 1; 
        }

        .message-card {
            background: #f4f4f4;
            border: 1px solid #ddd;
            padding: 10px;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.3s ease;
        }

        .message-card:hover {
            background: #e1e1e1;
        }

        .message-card a {
            display: block;
            margin-top: 10px;
        }

        .button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-align: center;
            margin-right: 10px;
        }

        .button:hover {
            background-color: #45a049;
        }

        .button-danger {
    background-color: red !important;
    color: white !important;
}

        .button-danger:hover {
            background-color: darkred;
        }

        .button-primary {
            background-color: blue;
            color: white;
        }

        .button-primary:hover {
            background-color: darkblue;
        }

        .message-card p {
            font-size: 14px;
            color: #333;
        }

        .message-card strong {
            font-size: 16px;
            color: #0073aa;
        }

        .button-container {
            display: flex;
            gap: 10px;
            justify-content: flex-start;
            margin-top: 20px; /* Abstand nach den Nachrichtenschaltflächen */
        }

        #messagePopup {
            display: none;
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            z-index: 999;
        }

        .message-form {
            margin-bottom: 30px; /* Abstand zum nächsten Inhalt */
        }
    </style>

    <div class="wrap">
        <h2>Pinwand</h2>

        <h3>Neue Nachricht erstellen</h3>
        <form class="message-form" method="post">
            <textarea name="new_message" rows="5" cols="50" required></textarea><br><br>
            <input type="submit" name="submit_message" value="Nachricht erstellen" class="button button-primary">
        </form>

        <?php
        global $wpdb;
        $table_name = $wpdb->prefix . 'message_board';
        $messages = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC");

        if ($messages) {
            echo '<div class="message-board">';
            foreach ($messages as $message) {
                $user_info = get_userdata($message->user_id);
                echo '<div class="message-card" onclick="openMessagePopup(' . $message->id . ')">'; 
                echo '<strong>' . esc_html($user_info->user_login) . ' (' . date('d-m-Y H:i:s', strtotime($message->created_at)) . ')</strong>';
                echo '<p>' . wp_trim_words($message->message, 20) . '...</p>';  // Zeige nur eine Vorschau
                echo '</div>';
            }
            echo '</div>';
        } else {
            echo '<p>Keine Nachrichten vorhanden.</p>';
        }
        ?>

    </div>

    <div id="messagePopup">
        <div id="messageContent"></div>
        <form id="editMessageForm" style="display:none;" method="post">
            <textarea name="message" id="messageText" rows="10" cols="50" required></textarea><br><br>
            <input type="submit" value="Nachricht aktualisieren" class="button button-primary">
        </form>
        <div class="button-container">
            <button onclick="closeMessagePopup()" class="button button-primary">Schließen</button>
            <button id="deleteMessageBtn" class="button button-danger" onclick="deleteMessage()">Löschen</button>
        </div>
    </div>

    <script>
        function openMessagePopup(messageId) {
            var data = {
                'action': 'wp_multi_get_message',
                'message_id': messageId
            };

            jQuery.post(ajaxurl, data, function(response) {
                var messageData = JSON.parse(response);
                document.getElementById('messageContent').innerHTML = '<h3>' + messageData.created_at + ' (' + messageData.user + ')</h3><p>' + messageData.message + '</p>';
                document.getElementById('messageText').value = messageData.message;
                document.getElementById('messagePopup').style.display = 'block';
                document.getElementById('editMessageForm').style.display = 'block';
                document.getElementById('deleteMessageBtn').setAttribute('data-message-id', messageId);
            });
        }

        function closeMessagePopup() {
            document.getElementById('messagePopup').style.display = 'none';
        }

        function deleteMessage() {
            var messageId = document.getElementById('deleteMessageBtn').getAttribute('data-message-id');

            var data = {
                'action': 'wp_multi_delete_message',
                'message_id': messageId
            };

            jQuery.post(ajaxurl, data, function(response) {
                if (response == 'success') {
                    closeMessagePopup();
                    location.reload();
                }
            });
        }
    </script>
    <?php
    // Nachricht erstellen
    if (isset($_POST['submit_message']) && !empty($_POST['new_message'])) {
        $new_message = sanitize_text_field($_POST['new_message']);
        $user_id = get_current_user_id();

        global $wpdb;
        $table_name = $wpdb->prefix . 'message_board';
        $wpdb->insert(
            $table_name,
            array(
                'message' => $new_message,
                'user_id' => $user_id
            )
        );
        echo '<p>Nachricht wurde erfolgreich erstellt.</p>';
        echo "<script>window.location.reload();</script>"; // Seite neu laden
    }
}

// Menüeintrag im Adminbereich hinzufügen
function wp_multi_add_message_board_menu() {
    add_menu_page(
        'Pinwand', // Seitentitel
        'Pinwand', // Menüeintrag
        'manage_options', // Berechtigung
        'message-board', // Slug
        'wp_multi_add_message_board', // Callback
        'dashicons-bell', // Icon
        6 // Position im Menü
    );
}
add_action('admin_menu', 'wp_multi_add_message_board_menu');

// Funktion zum Abrufen der vollständigen Nachricht
function wp_multi_get_message() {
    if (isset($_POST['message_id'])) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'message_board';
        $message_id = intval($_POST['message_id']);
        $message = $wpdb->get_row("SELECT * FROM $table_name WHERE id = $message_id");

        if ($message) {
            // Datum im gewünschten Format (DD-MM-JJJJ HH:MM:SS)
            $formatted_date = date('d-m-Y H:i:s', strtotime($message->created_at));

            echo json_encode([
                'created_at' => $formatted_date,
                'message' => nl2br(esc_textarea($message->message)),
                'user' => get_userdata($message->user_id)->user_login
            ]);
        }
    }
    wp_die();
}

add_action('wp_ajax_wp_multi_get_message', 'wp_multi_get_message');

// Funktion zum Löschen einer Nachricht
function wp_multi_delete_message() {
    if (isset($_POST['message_id'])) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'message_board';
        $message_id = intval($_POST['message_id']);
        $wpdb->delete($table_name, array('id' => $message_id));

        echo 'success';
    }
    wp_die();
}
add_action('wp_ajax_wp_multi_delete_message', 'wp_multi_delete_message');

// Funktion zum Deaktivieren der Pinwand bei der Deinstallation
function wp_multi_delete_message_board_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'message_board';
    $wpdb->query("DROP TABLE IF EXISTS $table_name");
}
register_deactivation_hook(__FILE__, 'wp_multi_delete_message_board_table');

// Funktion, um das Dashboard-Widget zu registrieren
function wp_multi_dashboard_widget() {
    wp_add_dashboard_widget(
        'wp_multi_pinwand_widget',  // Widget-ID
        'Pinwand Übersicht',        // Widget-Titel
        'wp_multi_dashboard_widget_content'  // Callback-Funktion
    );
}
add_action('wp_dashboard_setup', 'wp_multi_dashboard_widget');

// Callback-Funktion, die den Inhalt des Widgets erstellt
function wp_multi_dashboard_widget_content() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'message_board';
    $messages = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC LIMIT 5");  // Zeige die neuesten 5 Nachrichten an

    if ($messages) {
        echo '<ul>';
        foreach ($messages as $message) {
            $user_info = get_userdata($message->user_id);
            echo '<li>';
            echo '<strong>' . esc_html($user_info->user_login) . ' (' . date('d-m-Y H:i:s', strtotime($message->created_at)) . ')</strong>: ';
            echo wp_trim_words($message->message, 10) . '...';  // Zeigt nur eine Vorschau der Nachricht
            echo '</li>';
        }
        echo '</ul>';
    } else {
        echo '<p>Keine neuen Nachrichten.</p>';
    }
}


/*
 * Benutzer-Analytics mit verbesserten Sicherheits-, Performance- und Benutzerfreundlichkeits-Features
 */


define('WP_MULTI_ANALYTICS_TABLE', $wpdb->prefix . 'wp_multi_user_analytics');

/**
 * Erstellt die Datenbanktabelle für Benutzer-Analytics.
 */
function wp_multi_create_analytics_table() {
    global $wpdb;
    $table_name = WP_MULTI_ANALYTICS_TABLE;
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        action varchar(255) NOT NULL,
        post_id bigint(20) DEFAULT NULL,
        timestamp datetime DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY  (id),
        INDEX idx_timestamp (timestamp),
        INDEX idx_action (action)
    ) $charset_collate;";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);
}
register_activation_hook(__FILE__, 'wp_multi_create_analytics_table');

/**
 * Verfolgt Benutzerinteraktionen (Kommentare und Beitragsaufrufe).
 *
 * @param int    $user_id Benutzer-ID.
 * @param string $action  Aktion (z. B. 'view', 'comment').
 * @param int    $post_id Beitrag-ID (optional).
 * @return bool Erfolg der Operation.
 */
function wp_multi_track_user_activity($user_id, $action, $post_id = null) {
    global $wpdb;
    $table_name = WP_MULTI_ANALYTICS_TABLE;

    $user_id = absint($user_id);
    $action = sanitize_text_field($action);
    $post_id = $post_id ? absint($post_id) : null;

    if ($action === 'view' && is_single()) {
        $post_id = get_the_ID();
    }

    if (!$user_id || !$action) {
        return false;
    }

    return $wpdb->insert(
        $table_name,
        array(
            'user_id'   => $user_id,
            'action'    => $action,
            'post_id'   => $post_id,
        ),
        array('%d', '%s', '%d')
    );
}

/**
 * Verfolgt Kommentar-Aktivitäten.
 *
 * @param int $comment_id Kommentar-ID.
 */
function wp_multi_comment_activity($comment_id) {
    $comment = get_comment($comment_id);
    $user_id = absint($comment->user_id);
    if ($user_id) {
        wp_multi_track_user_activity($user_id, 'comment', $comment->comment_post_ID);
    }
}
add_action('comment_post', 'wp_multi_comment_activity');

/**
 * Verfolgt Beitragsaufrufe.
 */
function wp_multi_post_view_activity() {
    if (is_single() && is_user_logged_in()) {
        $user_id = get_current_user_id();
        $post_id = get_the_ID();
        wp_multi_track_user_activity($user_id, 'view', $post_id);
    }
}
add_action('wp_head', 'wp_multi_post_view_activity');

/**
 * Ruft rohe Analytics-Daten aus der Datenbank ab.
 *
 * @param string $date_query Datum für die Abfrage.
 * @return array Rohe Analytics-Daten.
 */
function wp_multi_fetch_raw_analytics($date_query = 'CURDATE() - INTERVAL 7 DAY') {
    global $wpdb;
    return $wpdb->get_results(
        $wpdb->prepare(
            "SELECT DATE(timestamp) AS date, action, post_id, COUNT(*) AS count, user_id, timestamp
             FROM " . WP_MULTI_ANALYTICS_TABLE . "
             WHERE timestamp >= %s 
             GROUP BY date, action, post_id, user_id, timestamp 
             ORDER BY date ASC",
            date('Y-m-d H:i:s', strtotime($date_query))
        )
    );
}

/**
 * Verarbeitet rohe Analytics-Daten für Diagramm und Tabelle.
 *
 * @param array $results Rohe Analytics-Daten.
 * @return array Verarbeitete Daten.
 */
function wp_multi_process_analytics_data($results) {
    $dates = [];
    $comment_counts = [];
    $view_counts = [];

    foreach ($results as $result) {
        $date = $result->date;
        if (!in_array($date, $dates)) {
            $dates[] = $date;
        }
        if ($result->action === 'comment') {
            $comment_counts[$date] = ($comment_counts[$date] ?? 0) + $result->count;
        } elseif ($result->action === 'view') {
            $view_counts[$date] = ($view_counts[$date] ?? 0) + $result->count;
        }
    }

    $all_dates = [];
    $datasets = ['comments' => [], 'views' => []];

    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i day"));
        $all_dates[] = $date;
        $datasets['comments'][] = $comment_counts[$date] ?? 0;
        $datasets['views'][] = $view_counts[$date] ?? 0;
    }

    return [
        'dates' => array_reverse($all_dates),
        'datasets' => [
            [
                'label' => __('Kommentare', 'wp-multi'),
                'data' => array_reverse($datasets['comments']),
                'borderColor' => 'rgba(75, 192, 192, 1)',
                'borderWidth' => 1,
                'fill' => false,
            ],
            [
                'label' => __('Beitragsaufrufe', 'wp-multi'),
                'data' => array_reverse($datasets['views']),
                'borderColor' => 'rgba(153, 102, 255, 1)',
                'borderWidth' => 1,
                'fill' => false,
            ]
        ],
        'data' => $results
    ];
}

/**
 * Ruft Analytics-Daten mit Caching ab.
 *
 * @param string $date_query Datum für die Abfrage.
 * @return array Analytics-Daten.
 */
function wp_multi_get_analytics_data($date_query = 'CURDATE() - INTERVAL 7 DAY') {
    $cache_key = 'wp_multi_analytics_data_' . md5($date_query);
    $cached_data = get_transient($cache_key);

    if ($cached_data !== false) {
        return $cached_data;
    }

    $results = wp_multi_fetch_raw_analytics($date_query);
    $data = wp_multi_process_analytics_data($results);

    set_transient($cache_key, $data, HOUR_IN_SECONDS);
    return $data;
}

/**
 * Zeigt die Benutzer-Analytics-Seite im Admin-Bereich an.
 */
function wp_multi_display_user_analytics() {
    global $wpdb;

    if (!$wpdb->get_var("SHOW TABLES LIKE '" . WP_MULTI_ANALYTICS_TABLE . "'")) {
        echo '<div class="error"><p>' . esc_html__('Die Analytics-Tabelle existiert nicht. Bitte aktiviere das Plugin erneut.', 'wp-multi') . '</p></div>';
        return;
    }

    $time_range = isset($_GET['time_range']) ? sanitize_text_field($_GET['time_range']) : '7days';
    $date_query = 'CURDATE() - INTERVAL 7 DAY';
    if ($time_range === '30days') {
        $date_query = 'CURDATE() - INTERVAL 30 DAY';
    } elseif ($time_range === 'custom' && isset($_GET['start_date'], $_GET['end_date'])) {
        $start_date = sanitize_text_field($_GET['start_date']);
        $end_date = sanitize_text_field($_GET['end_date']);
        $date_query = "$start_date AND $end_date";
    }

    $results = wp_multi_get_analytics_data($date_query);

    ?>
    <div class="wrap">
        <div style="background-color: #0073aa; padding: 20px; text-align: center; color: white;">
            <img src="https://m-viper.de/img/logo.png" alt="Logo" style="height: 50px; vertical-align: middle;">
            <h1 style="display: inline; margin-left: 10px;"><?php esc_html_e('Benutzer Analytics', 'wp-multi'); ?></h1>
        </div>

        <form method="get">
            <input type="hidden" name="page" value="wp_multi_analytics">
            <select name="time_range" onchange="this.form.submit()">
                <option value="7days" <?php selected($time_range, '7days'); ?>><?php esc_html_e('Letzte 7 Tage', 'wp-multi'); ?></option>
                <option value="30days" <?php selected($time_range, '30days'); ?>><?php esc_html_e('Letzte 30 Tage', 'wp-multi'); ?></option>
                <option value="custom" <?php selected($time_range, 'custom'); ?>><?php esc_html_e('Benutzerdefiniert', 'wp-multi'); ?></option>
            </select>
            <?php if ($time_range === 'custom') : ?>
                <input type="date" name="start_date" value="<?php echo esc_attr($_GET['start_date'] ?? ''); ?>">
                <input type="date" name="end_date" value="<?php echo esc_attr($_GET['end_date'] ?? ''); ?>">
            <?php endif; ?>
            <button type="submit"><?php esc_html_e('Filtern', 'wp-multi'); ?></button>
        </form>

        <?php if (empty($results['data'])) : ?>
            <p><?php esc_html_e('Keine Daten verfügbar.', 'wp-multi'); ?></p>
        <?php else : ?>
            <canvas id="userActivityChart" style="height: 300px; width: 100%;"></canvas>
            <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
            <script>
                if (typeof Chart !== 'undefined') {
                    document.addEventListener('DOMContentLoaded', function () {
                        var ctx = document.getElementById('userActivityChart').getContext('2d');
                        var chart = new Chart(ctx, {
                            type: 'line',
                            data: {
                                labels: <?php echo wp_json_encode($results['dates']); ?>,
                                datasets: <?php echo wp_json_encode($results['datasets']); ?>,
                            },
                            options: {
                                scales: {
                                    x: { title: { display: true, text: '<?php echo esc_js(__('Datum', 'wp-multi')); ?>' } },
                                    y: { title: { display: true, text: '<?php echo esc_js(__('Anzahl', 'wp-multi')); ?>' }, beginAtZero: true }
                                }
                            }
                        });
                    });
                } else {
                    console.error('Chart.js konnte nicht geladen werden.');
                }
            </script>

            <table class="widefat">
                <thead>
                    <tr>
                        <th><?php esc_html_e('Benutzer ID', 'wp-multi'); ?></th>
                        <th><?php esc_html_e('Aktion', 'wp-multi'); ?></th>
                        <th><?php esc_html_e('Beitrag Titel', 'wp-multi'); ?></th>
                        <th><?php esc_html_e('Beitrag ID', 'wp-multi'); ?></th>
                        <th><?php esc_html_e('Zeitstempel', 'wp-multi'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($results['data'] as $index => $row) : ?>
                        <tr style="background-color: <?php echo ($index % 2 == 0) ? '#f9f9f9' : '#ffffff'; ?>;">
                            <td><?php echo esc_html($row->user_id); ?></td>
                            <td><?php echo esc_html($row->action); ?></td>
                            <td>
                                <?php
                                if ($row->post_id) {
                                    $post_title = get_the_title($row->post_id);
                                    echo esc_html($post_title ?: __('Kein Titel verfügbar', 'wp-multi'));
                                } else {
                                    echo esc_html__('Kein Beitrag', 'wp-multi');
                                }
                                ?>
                            </td>
                            <td><?php echo esc_html($row->post_id ?: '-'); ?></td>
                            <td><?php echo esc_html($row->timestamp); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Fügt die Analytics-Seite zum Admin-Menü hinzu.
 */
function wp_multi_add_analytics_page() {
    add_submenu_page(
        'users.php',
        __('Benutzer Analytics', 'wp-multi'),
        __('Benutzer Analytics', 'wp-multi'),
        'manage_options',
        'wp_multi_analytics',
        'wp_multi_display_user_analytics'
    );
}
add_action('admin_menu', 'wp_multi_add_analytics_page');








/*
 * 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( __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']);
}

function wp_multi_register_blocked_users_page() {
    add_menu_page(
        'Gesperrte Benutzer',
        'Gesperrte Benutzer',
        'manage_options',
        'wp-multi-blocked-users',
        'wp_multi_blocked_users_page',
        'dashicons-shield',
        80
    );
}
add_action('admin_menu', 'wp_multi_register_blocked_users_page');

function wp_multi_blocked_users_page() {
    global $wpdb;

    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)) {
            echo '<div class="updated"><p>Benutzer wurde gesperrt!</p></div>';
        } else {
            echo '<div class="error"><p>Fehler beim Sperren des Benutzers!</p></div>';
        }
    }

    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)) {
                echo '<div class="updated"><p>Benutzer wurde gelöscht!</p></div>';
            } else {
                echo '<div class="error"><p>Fehler beim Löschen des Benutzers!</p></div>';
            }
        }
    }

    $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 . '%'
    ));

    ?>
    <div class="wrap">
        <h2>Benutzer sperren</h2>
        <form method="post">
            <?php wp_nonce_field('wp_multi_block_user'); ?>
            <h3>Benutzernamen sperren</h3>
            <input type="text" name="block_username" class="regular-text" placeholder="Benutzername">
            <h3>E-Mail-Adresse sperren</h3>
            <input type="email" name="block_email" class="regular-text" placeholder="E-Mail-Adresse">
            <h3>IP-Adresse sperren</h3>
            <input type="text" name="block_ip" class="regular-text" placeholder="IP-Adresse">
            <br><br>
            <input type="submit" class="button button-primary" value="Benutzer sperren">
        </form>
        <h2>Gesperrte Benutzer</h2>
        <form method="get">
            <input type="hidden" name="page" value="wp-multi-blocked-users">
            <input type="text" name="search" value="<?php echo esc_attr($search_query); ?>" placeholder="Benutzername, E-Mail oder IP suchen" class="regular-text">
            <input type="submit" class="button" value="Suchen">
        </form>
        <table class="widefat">
            <thead>
                <tr>
                    <th>Benutzername</th>
                    <th>E-Mail-Adresse</th>
                    <th>IP-Adresse</th>
                    <th>Aktionen</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 wp_nonce_url(admin_url('admin.php?page=wp-multi-blocked-users&delete=' . $user->id), 'wp_multi_delete_user_' . $user->id); ?>" class="button button-secondary">Löschen</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else : ?>
                    <tr>
                        <td colspan="4">Keine gesperrten Benutzer gefunden.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
}

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');


/*
* custom shortcodes
*/


// Funktion, um die Datenbanktabelle für Shortcodes zu erstellen
function wp_multi_create_shortcodes_table() {
    global $wpdb;

    $table_name = $wpdb->prefix . 'wp_multi_shortcodes'; // Name der Tabelle mit Präfix
    $charset_collate = $wpdb->get_charset_collate();

    // SQL-Abfrage zum Erstellen der Tabelle
    $sql = "CREATE TABLE $table_name (
        id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        shortcode_name varchar(255) NOT NULL,
        shortcode_content text NOT NULL,
        PRIMARY KEY  (id),
        UNIQUE KEY shortcode_name (shortcode_name)
    ) $charset_collate;";

    // Datenbank abfragen und ausführen
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
}
register_activation_hook( __FILE__, 'wp_multi_create_shortcodes_table' );

// Menü zum Verwalten von Shortcodes im Admin-Bereich hinzufügen
function wp_multi_add_shortcode_menu() {
    add_menu_page(
        'Custom Shortcodes',         // Seitentitel
        'Custom Shortcodes',         // Menü-Titel
        'manage_options',            // Berechtigungen
        'wp_multi_shortcodes',       // Menü-Slug
        'wp_multi_shortcode_page',   // Callback-Funktion zum Anzeigen der Seite
        'dashicons-editor-code',     // Symbol
        6                            // Position im Menü
    );
}
add_action('admin_menu', 'wp_multi_add_shortcode_menu');

// Callback-Funktion für das Shortcode-Verwaltungs-Interface
function wp_multi_shortcode_page() {
    global $wpdb;

    $message = ''; // Variable für benutzerdefinierte Nachrichten

    // Verarbeite das Speichern von Shortcodes
    if (isset($_POST['wp_multi_shortcode_name']) && isset($_POST['wp_multi_shortcode_content'])) {
        // Hole die übermittelten Shortcodes
        $name = sanitize_text_field($_POST['wp_multi_shortcode_name']);
        $content = sanitize_textarea_field($_POST['wp_multi_shortcode_content']);
        
        // Prüfen, ob der Shortcode bereits existiert
        $existing_shortcode = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$wpdb->prefix}wp_multi_shortcodes WHERE shortcode_name = %s", $name));

        if ($existing_shortcode) {
            // Aktualisiere den Shortcode, falls er bereits existiert
            $wpdb->update(
                $wpdb->prefix . 'wp_multi_shortcodes',
                ['shortcode_content' => $content],
                ['shortcode_name' => $name]
            );
            $message = 'Shortcode wurde aktualisiert!';
        } else {
            // Andernfalls einen neuen Shortcode einfügen
            $wpdb->insert(
                $wpdb->prefix . 'wp_multi_shortcodes',
                [
                    'shortcode_name' => $name,
                    'shortcode_content' => $content
                ]
            );
            $message = 'Shortcode wurde hinzugefügt!';
        }
    }

    // Shortcode löschen
    if (isset($_GET['delete_shortcode']) && !empty($_GET['delete_shortcode'])) {
        $delete_id = intval($_GET['delete_shortcode']);
        $wpdb->delete(
            $wpdb->prefix . 'wp_multi_shortcodes',
            ['id' => $delete_id]
        );
        $message = 'Shortcode wurde gelöscht!';
    }

    // Holen der gespeicherten Shortcodes aus der Datenbank
    $custom_shortcodes = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wp_multi_shortcodes");

    // HTML für die Seite
    ?>
    <div class="wrap wp-multi-admin-page">
        <h1><?php _e('WP Multi - Shortcodes Einstellungen', 'wp-multi'); ?></h1>

        <!-- Gemeinsame Box für Logo und Banner -->
        <div class="wp-multi-header-box">
            <div class="wp-multi-banner">
                <img src="https://m-viper.de/img/logo.png" alt="M_Viper Logo" class="wp-multi-logo" />
                <h1>Custom Shortcodes verwalten</h1>
            </div>
        </div>

        <!-- Benachrichtigungen und Standard-WordPress-Nachrichten -->
        <?php if (!empty($message)) : ?>
            <div class="wp-multi-custom-message">
                <p><?php echo esc_html($message); ?></p>
            </div>
        <?php endif; ?>

        <form method="post">
            <table class="form-table wp-multi-table">
                <tr>
                    <th><label for="wp_multi_shortcode_name">Name des Shortcodes</label></th>
                    <td><input type="text" name="wp_multi_shortcode_name" id="wp_multi_shortcode_name" class="regular-text" required /></td>
                </tr>
                <tr>
                    <th><label for="wp_multi_shortcode_content">Inhalt des Shortcodes</label></th>
                    <td><textarea name="wp_multi_shortcode_content" id="wp_multi_shortcode_content" class="large-text" rows="5" required></textarea></td>
                </tr>
            </table>
            <?php submit_button('Shortcode speichern'); ?>
        </form>

        <h2>Verfügbare Shortcodes</h2>
        <ul class="wp-multi-shortcodes-list">
            <?php
            if (!empty($custom_shortcodes)) {
                foreach ($custom_shortcodes as $shortcode) {
                    echo '<li><strong>' . esc_html($shortcode->shortcode_name) . ':</strong> ' . esc_html($shortcode->shortcode_content) . ' 
                        <a href="' . esc_url(admin_url('admin.php?page=wp_multi_shortcodes&delete_shortcode=' . $shortcode->id)) . '" class="wp-multi-delete-button" onclick="return confirm(\'Möchten Sie diesen Shortcode wirklich löschen?\');">Löschen</a></li>';
                }
            } else {
                echo '<li>Keine benutzerdefinierten Shortcodes gefunden.</li>';
            }
            ?>
        </ul>
    </div>

    <style>
        /* Container für Logo und Banner in einer Box */
        .wp-multi-header-box {
            text-align: center;
            margin-top: 20px;
            padding: 20px;
            background-color: #f1f1f1;
        }

        .wp-multi-logo {
            max-height: 80px;
        }

        /* Banner-Stil */
        .wp-multi-banner {
            background-color: #0073aa; /* Blaues Banner */
            padding: 10px;
            text-align: center;
            margin-top: 20px;
        }

        .wp-multi-banner h1 {
            font-size: 30px;
            margin: 0;
            font-weight: 600;
        }

        /* Benutzerdefinierte Nachrichtenbox */
        .wp-multi-custom-message {
            background-color: #f1f1f1;
            padding: 15px;
            border-left: 4px solid #0073aa;
            margin: 20px 0;
            font-size: 16px;
        }

        /* Anpassungen für die Formularfelder */
        .form-table {
            margin-top: 30px;
        }

        .form-table th {
            width: 220px;
            font-weight: bold;
        }

        .form-table td {
            width: auto;
        }

        .wp-multi-table input, .wp-multi-table textarea {
            width: 100%;
            border-radius: 5px;
            padding: 10px;
            border: 1px solid #ccc;
        }

        .wp-multi-table input:focus, .wp-multi-table textarea:focus {
            border-color: #0073aa;
        }

        .wp-multi-shortcodes-list {
            list-style-type: none;
            margin-top: 30px;
            padding-left: 0;
        }

        .wp-multi-shortcodes-list li {
            background-color: #f9f9f9;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
        }

        .wp-multi-shortcodes-list li:hover {
            background-color: #f1f1f1;
        }

        /* Löschen-Button Stil */
        .wp-multi-delete-button {
            color: #ff0000;
            margin-left: 10px;
            text-decoration: none;
        }

        .wp-multi-delete-button:hover {
            text-decoration: underline;
        }

        /* Anpassen des Buttons */
        .button-primary {
            background-color: #0073aa;
            border-color: #0073aa;
        }

        .button-primary:hover {
            background-color: #005f8d;
            border-color: #005f8d;
        }
    </style>

<?php
}

// Shortcode-Verwaltung: Ermöglicht Benutzern das Erstellen eigener Shortcodes
function wp_multi_register_custom_shortcodes() {
    global $wpdb;

    // Holen der gespeicherten Shortcodes aus der Datenbank
    $custom_shortcodes = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}wp_multi_shortcodes");

    // Wenn keine benutzerdefinierten Shortcodes vorhanden sind, abbrechen
    if (empty($custom_shortcodes)) {
        return;
    }

    // Definiere die Shortcodes in WordPress
    foreach ($custom_shortcodes as $shortcode) {
        add_shortcode($shortcode->shortcode_name, function() use ($shortcode) {
            return $shortcode->shortcode_content;
        });
    }
}
add_action('init', 'wp_multi_register_custom_shortcodes');

// Inhalt der Meta-Box anzeigen
function wp_multi_render_shortcode_meta_box($post) {
    global $wpdb;

    // Alle gespeicherten Shortcodes aus der Datenbank holen
    $shortcodes = $wpdb->get_results("SELECT shortcode_name FROM {$wpdb->prefix}wp_multi_shortcodes");

    if (!empty($shortcodes)) {
        echo '<select id="wp_multi_shortcode_dropdown">';
        echo '<option value="">-- Shortcode auswählen --</option>';

        foreach ($shortcodes as $shortcode) {
            echo '<option value="' . esc_attr($shortcode->shortcode_name) . '">' . esc_html($shortcode->shortcode_name) . '</option>';
        }

        echo '</select>';
        echo '<button type="button" class="button button-primary" id="wp_multi_insert_shortcode">Einfügen</button>';
    } else {
        echo '<p>Keine Shortcodes vorhanden.</p>';
    }
}

    // JavaScript für Meta-Box einbinden
function wp_multi_enqueue_admin_scripts($hook) {
    if ('post.php' === $hook || 'post-new.php' === $hook) {
        wp_enqueue_script('wp-multi-shortcode', plugin_dir_url(__FILE__) . 'js/editor-shortcode.js', array('jquery'), null, true);
    }
}
add_action('admin_enqueue_scripts', 'wp_multi_enqueue_admin_scripts');

// Funktion zum Registrieren des TinyMCE Plugins
function wp_multi_add_shortcode_button() {
    add_filter('mce_external_plugins', 'wp_multi_register_tinymce_plugin');
    add_filter('mce_buttons', 'wp_multi_add_tinymce_button');
}
add_action('admin_head', 'wp_multi_add_shortcode_button');

// Plugin für TinyMCE registrieren (angepasster Pfad zum JS-File)
function wp_multi_register_tinymce_plugin($plugins) {
    $plugins['wp_multi_shortcodes'] = plugin_dir_url(__FILE__) . 'js/tinymce-shortcodes.js';
    return $plugins;
}

// Button zur TinyMCE Toolbar hinzufügen
function wp_multi_add_tinymce_button($buttons) {
    array_push($buttons, 'wp_multi_shortcodes');
    return $buttons;
}

// Shortcodes aus der Datenbank für das JavaScript bereitstellen
function wp_multi_localize_shortcodes() {
    global $wpdb;
    $shortcodes = $wpdb->get_results("SELECT shortcode_name FROM {$wpdb->prefix}wp_multi_shortcodes", ARRAY_A);
    
    // Shortcodes als JSON an das JS-File übergeben
    wp_enqueue_script('wp-multi-tinymce', plugin_dir_url(__FILE__) . 'js/tinymce-shortcodes.js', array('jquery'), null, true);
    wp_localize_script('wp-multi-tinymce', 'wpMultiShortcodes', $shortcodes);
}
add_action('admin_enqueue_scripts', 'wp_multi_localize_shortcodes');


/*
* Notify Seite Discord & Telegram
*/


// Übergeordnetes Menü "Notify" erstellen
function wp_multi_menu() {
    // Menüpunkt für "Notify"
    add_menu_page(
        'Notify',           
        'Notify',           
        'manage_options',   
        'wp-multi-notify',  
        'wp_multi_notify_page',  
        'dashicons-bell',   
        100                 
    );

    // Untermenüpunkt für DC-Notify
    add_submenu_page(
        'wp-multi-notify',             
        'DC-Notify Einstellungen',     
        'DC-Notify',                   
        'manage_options',              
        'wp-multi',                    
        'wp_multi_settings_page'       
    );

    // Untermenüpunkt für TG-Notify
    add_submenu_page(
        'wp-multi-notify',             
        'TG-Notify Einstellungen',     
        'TG-Notify',                   
        'manage_options',              
        'tg-notify',                   
        'tg_notify_page'               
    );
}
add_action('admin_menu', 'wp_multi_menu');

// Callback-Funktion für die Hauptseite Notify
function wp_multi_notify_page() {
    ?>
    <div class="wrap wp-multi-admin-page">
        <h1><?php _e('WP Multi - Notify Einstellungen', 'wp-multi'); ?></h1>

        <!-- Blaues Banner hinter dem Logo -->
        <div class="wp-multi-banner">
            <img src="https://m-viper.de/img/logo.png" alt="M_Viper Logo" class="wp-multi-logo-image" />
        </div>

        <div class="wp-multi-settings-header">
            <h2><?php _e('Einrichtung von Discord und Telegram Benachrichtigungen', 'wp-multi'); ?></h2>
            <p><?php _e('Um Benachrichtigungen zu Discord oder Telegram zu senden, müssen Sie zuerst die entsprechenden Webhooks und Bots einrichten. Diese Seite gibt Ihnen nur eine Übersicht und Anleitung, wie dies zu tun ist.', 'wp-multi'); ?></p>

            <h3><?php _e('Discord', 'wp-multi'); ?></h3>
            <p><?php _e('Erstellen Sie einen Webhook in einem Discord-Kanal und fügen Sie die Webhook-URL in die entsprechenden Felder ein.', 'wp-multi'); ?></p>
            <ol>
                <li><?php _e('Gehen Sie zu Ihrem Discord-Server und öffnen Sie die Server-Einstellungen.', 'wp-multi'); ?></li>
                <li><?php _e('Wählen Sie "Integrationen" und dann "Webhook erstellen".', 'wp-multi'); ?></li>
                <li><?php _e('Kopieren Sie die Webhook-URL und fügen Sie diese in das entsprechende Feld auf dieser Seite ein.', 'wp-multi'); ?></li>
            </ol>

            <h3><?php _e('Telegram', 'wp-multi'); ?></h3>
            <p><?php _e('Erstellen Sie einen Bot über BotFather und fügen Sie den Token und die Kanal-ID in die entsprechenden Felder ein.', 'wp-multi'); ?></p>
            <ol>
                <li><?php _e('Öffnen Sie Telegram und suchen Sie nach "BotFather".', 'wp-multi'); ?></li>
                <li><?php _e('Geben Sie /newbot ein, um einen neuen Bot zu erstellen.', 'wp-multi'); ?></li>
                <li><?php _e('Speichern Sie den Bot-Token und die Kanal-ID und tragen Sie diese in die Felder oben ein.', 'wp-multi'); ?></li>
            </ol>
        </div>
    </div>
    <?php
}

/*
 * Discord Notify
 */

// Callback-Funktion für die DC-Notify Seite
function wp_multi_dc_notify_page() {
    ?>
    <div class="wrap wp-multi-admin-page">
        <h1><?php _e('DC-Notify Einstellungen', 'wp-multi'); ?></h1>
        <!-- Blaues Banner hinter dem Logo -->
        <div class="wp-multi-banner">
            <img src="https://m-viper.de/img/logo.png" alt="M_Viper Logo" class="wp-multi-logo-image" />
        </div>
        <p><?php _e('Hier können Sie Discord-Benachrichtigungen konfigurieren. Weitere Anweisungen finden Sie unten.', 'wp-multi'); ?></p>
        <h2><?php _e('Discord Setup Anleitung', 'wp-multi'); ?></h2>
        <ol>
            <li><?php _e('Gehen Sie zu Ihrem Discord-Server und öffnen Sie die Server-Einstellungen.', 'wp-multi'); ?></li>
            <li><?php _e('Wählen Sie "Integrationen" und dann "Webhook erstellen".', 'wp-multi'); ?></li>
            <li><?php _e('Kopieren Sie die Webhook-URL und fügen Sie diese in das entsprechende Feld ein.', 'wp-multi'); ?></li>
        </ol>
    </div>
    <?php
}

// CSS für das Plugin
function wp_multi_admin_styles() {
    echo '
    <style>
        .wp-multi-admin-page {
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
        }
        .wp-multi-banner {
            background-color: #0073aa;
            padding: 10px;
            text-align: center;
            margin-bottom: 20px;
        }
        .wp-multi-logo-image {
            width: 200px;
            height: auto;
            display: inline-block;
        }
        .wp-multi-settings-header h2 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
        }
        .wp-multi-settings-header ol {
            margin-left: 20px;
        }
        .wp-multi-settings-header ol li {
            margin-bottom: 8px;
        }
    </style>
    ';
}
add_action('admin_head', 'wp_multi_admin_styles');

// Einstellungsseite für Discord Webhook
function wp_multi_settings_page() {
    ?>
    <div class="wrap">
        <!-- Header mit Banner und Logo -->
        <div class="wp-multi-settings-header">
            <div class="wp-multi-logo">
                <img src="https://m-viper.de/img/logo.png" alt="Logo" />
            </div>
        </div>

        <form method="post" action="options.php">
            <?php
            settings_fields('wp_multi_discord_options_group');
            do_settings_sections('wp-multi');
            ?>
            <table class="form-table">
                <tr>
                    <th scope="row">Discord Webhook URL</th>
                    <td>
                        <input type="text" name="wp_multi_discord_webhook" value="<?php echo esc_attr(get_option('wp_multi_discord_webhook')); ?>" size="50">
                        <p class="description">Geben Sie die Webhook-URL für Discord ein, um Benachrichtigungen zu senden.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Bot Name</th>
                    <td>
                        <input type="text" name="wp_multi_discord_bot_name" value="<?php echo esc_attr(get_option('wp_multi_discord_bot_name', 'WP Multi Bot')); ?>" size="50">
                        <p class="description">Geben Sie den Namen des Bots ein, der in Discord angezeigt werden soll.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Discord Nachricht (Vorlage)</th>
                    <td>
                        <textarea name="wp_multi_discord_message_template" rows="4" cols="50"><?php echo esc_textarea(get_option('wp_multi_discord_message_template', 'Beitrag "{post_title}" von {post_author} | Link: {post_url}')); ?></textarea>
                        <p class="description">Passen Sie die Nachricht an, die an Discord gesendet wird. Verwenden Sie Platzhalter wie {post_title}, {post_author}, und {post_url}.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Discord Benutzerrollen ID (für Ping)</th>
                    <td>
                        <input type="text" name="wp_multi_discord_role_id" value="<?php echo esc_attr(get_option('wp_multi_discord_role_id')); ?>" size="50">
                        <p class="description">Geben Sie die ID der Discord-Benutzerrolle ein, die gepingt werden soll (z. B. @everyone).</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Discord Avatar-URL</th>
                    <td>
                        <input type="text" name="wp_multi_discord_avatar_url" value="<?php echo esc_attr(get_option('wp_multi_discord_avatar_url')); ?>" size="50">
                        <p class="description">Geben Sie die URL des Avatar-Bildes ein, das in den Discord-Nachrichten angezeigt werden soll.</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Footer Text (Custom Text 2)</th>
                    <td>
                        <input type="text" name="wp_multi_discord_footer_text" value="<?php echo esc_attr(get_option('wp_multi_discord_footer_text')); ?>" size="50">
                        <p class="description">Geben Sie den benutzerdefinierten Text ein, der am Ende der Nachricht angezeigt wird (z. B. "Powered by WP Multi"). Sie können auch Platzhalter wie {post_title}, {post_author} und {post_url} verwenden.</p>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <style>
        .wp-multi-settings-header {
            background-color: #0073aa;
            padding: 50px 20px;
            text-align: center;
            position: relative;
            margin-bottom: 30px;
        }
        .wp-multi-settings-header::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #0073aa;
            z-index: -1;
        }
        .wp-multi-logo img {
            max-width: 200px;
            display: block;
            margin: 0 auto;
        }
        .wrap .form-table {
            background-color: #f9f9f9;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .wrap .form-table th {
            font-weight: bold;
        }
        .wrap .form-table td {
            padding: 10px;
        }
        .wrap .form-table input[type="text"],
        .wrap .form-table textarea {
            width: 100%;
            padding: 10px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .wrap .form-table input[type="text"]:focus,
        .wrap .form-table textarea:focus {
            border-color: #1e3a8a;
        }
        .wrap .description {
            font-style: italic;
            color: #666;
        }
        .wrap .button-primary {
            background-color: #1e3a8a;
            border-color: #1e3a8a;
            box-shadow: none;
        }
        .wrap .button-primary:hover {
            background-color: #2563eb;
            border-color: #2563eb;
        }
    </style>
    <?php
}

// Funktion, um die Einstellungen zu registrieren
function wp_multi_register_settings() {
    register_setting('wp_multi_discord_options_group', 'wp_multi_discord_webhook');
    register_setting('wp_multi_discord_options_group', 'wp_multi_discord_bot_name');
    register_setting('wp_multi_discord_options_group', 'wp_multi_discord_message_template');
    register_setting('wp_multi_discord_options_group', 'wp_multi_discord_role_id');
    register_setting('wp_multi_discord_options_group', 'wp_multi_discord_avatar_url');
    register_setting('wp_multi_discord_options_group', 'wp_multi_discord_footer_text');
}
add_action('admin_init', 'wp_multi_register_settings');

// Funktion, um die Discord-Benachrichtigung zu senden
function wp_multi_send_discord_notification($ID, $post) {
    $send_notification = get_post_meta($ID, '_wp_multi_checkbox', true);
    if ($send_notification !== '1') {
        return;
    }

    $webhook_url = get_option('wp_multi_discord_webhook');
    if (empty($webhook_url)) {
        return;
    }

    $bot_name = get_option('wp_multi_discord_bot_name', 'WP Multi Bot');
    $avatar_url = get_option('wp_multi_discord_avatar_url');
    $post_title = esc_html(get_the_title($ID));
    $post_url = esc_url(get_permalink($ID));
    $post_author = esc_html(get_the_author_meta('display_name', $post->post_author));
    $content = get_post_field('post_content', $ID);
    $excerpt = wp_trim_words($content, 60, '...');
    $role_id = get_option('wp_multi_discord_role_id');
    $mention_role = (!empty($role_id) && is_numeric($role_id)) ? "<@&" . esc_attr($role_id) . ">" : '';
    $footer_text = get_option('wp_multi_discord_footer_text');
    $footer = !empty($footer_text) ? str_replace(
        ['{post_title}', '{post_author}', '{post_url}'],
        [$post_title, $post_author, $post_url],
        $footer_text
    ) : '';

    $message_template = get_option('wp_multi_discord_message_template', 'Beitrag "{post_title}" von {post_author} | Link: {post_url}');
    $message = str_replace(
        ['{post_title}', '{post_author}', '{post_url}'],
        [$post_title, $post_author, $post_url],
        $message_template
    );
    $message .= "\n\n" . $excerpt . "\n\n" . $footer;

    $data = json_encode([
        'username' => $bot_name,
        'avatar_url' => $avatar_url,
        'content' => $mention_role . "\n" . $message
    ]);

    $response = wp_remote_post($webhook_url, [
        'method' => 'POST',
        'body' => $data,
        'headers' => ['Content-Type' => 'application/json']
    ]);

    if (!is_wp_error($response)) {
        wp_multi_increment_discord_message_count();
    } else {
        error_log('Discord Webhook Fehler: ' . $response->get_error_message());
    }
}
add_action('publish_post', 'wp_multi_send_discord_notification', 10, 2);

// Funktion zum Erhöhen des Discord-Nachrichtenzählers
function wp_multi_increment_discord_message_count() {
    $current_count = get_option('wp_multi_discord_message_count', 0);
    update_option('wp_multi_discord_message_count', $current_count + 1);
}

// Funktion, um die Checkbox in der Sidebar des Beitrag Editors hinzuzufügen
function wp_multi_add_checkbox_to_sidebar() {
    global $post;
    wp_nonce_field('wp_multi_checkbox_nonce', 'wp_multi_checkbox_nonce_field');
    $value = get_post_meta($post->ID, '_wp_multi_checkbox', true);
    ?>
    <div class="misc-pub-section">
        <label for="wp_multi_checkbox">
            <input type="checkbox" name="wp_multi_checkbox" id="wp_multi_checkbox" value="1" <?php checked($value, '1'); ?>>
            Discord Benachrichtigung senden
        </label>
    </div>
    <?php
}
add_action('post_submitbox_misc_actions', 'wp_multi_add_checkbox_to_sidebar');

// Funktion, um den Wert der Checkbox zu speichern
function wp_multi_save_checkbox_value($post_id) {
    if (!isset($_POST['wp_multi_checkbox_nonce_field']) || !wp_verify_nonce($_POST['wp_multi_checkbox_nonce_field'], 'wp_multi_checkbox_nonce')) {
        return;
    }
    if (isset($_POST['wp_multi_checkbox']) && $_POST['wp_multi_checkbox'] === '1') {
        update_post_meta($post_id, '_wp_multi_checkbox', '1');
    } else {
        delete_post_meta($post_id, '_wp_multi_checkbox');
    }
}
add_action('save_post', 'wp_multi_save_checkbox_value');

/*
* Telegram Notify
*/


// Admin-Seiten Callback
function tg_notify_page() {
    ?>
    <div class="wrap tg-notify-settings">
        <h1><?php _e('TG-Notify Einstellungen', 'wp-stat-notice'); ?></h1>
        <form method="post" action="options.php" class="tg-notify-form">
            <?php
            settings_fields('tg_notify_options_group');
            do_settings_sections('tg-notify');
            submit_button('Speichern', 'primary', 'submit', true);
            ?>
        </form>
    </div>
    <style>
        .tg-notify-settings {
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .tg-notify-settings h1 {
            font-size: 24px;
            margin-bottom: 20px;
            color: #333;
        }
        .tg-notify-form input,
        .tg-notify-form textarea {
            width: 100%;
            padding: 10px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .tg-notify-form textarea {
            resize: vertical;
        }
        .tg-notify-form label {
            font-weight: bold;
            margin-bottom: 5px;
            display: block;
        }
        .tg-notify-form p {
            font-size: 12px;
            color: #666;
        }
        .tg-notify-form input[type="checkbox"] {
            margin-right: 8px;
        }
        .tg-notify-settings .submit {
            background-color: #0073aa;
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }
        .tg-notify-settings .submit:hover {
            background-color: #005c8a;
        }
    </style>
    <?php
}

// Einstellungen registrieren
function tg_notify_register_settings() {
    register_setting('tg_notify_options_group', 'tg_notify_bot_name');
    register_setting('tg_notify_options_group', 'tg_notify_bot_token');
    register_setting('tg_notify_options_group', 'tg_notify_chat_ids');
    register_setting('tg_notify_options_group', 'tg_notify_custom_message');

    add_settings_section('tg_notify_main_section', __('Telegram Einstellungen', 'wp-stat-notice'), null, 'tg-notify');

    add_settings_field('tg_notify_bot_name', __('Bot Name', 'wp-stat-notice'), 'tg_notify_bot_name_callback', 'tg-notify', 'tg_notify_main_section');
    add_settings_field('tg_notify_bot_token', __('Bot Token', 'wp-stat-notice'), 'tg_notify_bot_token_callback', 'tg-notify', 'tg_notify_main_section');
    add_settings_field('tg_notify_chat_ids', __('Kanal IDs', 'wp-stat-notice'), 'tg_notify_chat_ids_callback', 'tg-notify', 'tg_notify_main_section');
    add_settings_field('tg_notify_custom_message', __('Custom Nachricht', 'wp-stat-notice'), 'tg_notify_custom_message_callback', 'tg-notify', 'tg_notify_main_section');
}
add_action('admin_init', 'tg_notify_register_settings');

// Callback-Funktionen
function tg_notify_bot_name_callback() {
    $value = get_option('tg_notify_bot_name', '');
    echo '<input type="text" name="tg_notify_bot_name" value="' . esc_attr($value) . '" class="regular-text">';
}
function tg_notify_bot_token_callback() {
    $value = get_option('tg_notify_bot_token', '');
    echo '<input type="text" name="tg_notify_bot_token" value="' . esc_attr($value) . '" class="regular-text">';
}
function tg_notify_chat_ids_callback() {
    $value = get_option('tg_notify_chat_ids', '');
    echo '<textarea name="tg_notify_chat_ids" class="large-text code" rows="3">' . esc_textarea($value) . '</textarea>';
	echo '<p>Kanal ohne Thema: -1001234567890</p>';
	echo '<p>Kanal mit Thema: -1001234567890_123</p>';
}
function tg_notify_custom_message_callback() {
    $value = get_option('tg_notify_custom_message', '');
    echo '<textarea name="tg_notify_custom_message" class="large-text code" rows="5">' . esc_textarea($value) . '</textarea>';
    echo '<p>Verfügbare Variablen: {title}, {author}, {link}</p>';
}

// Checkbox beim Beitrag hinzufügen
function tg_notify_add_meta_box() {
    add_meta_box(
        'tg_notify_meta_box',
        __('Telegram Benachrichtigung', 'wp-stat-notice'),
        'tg_notify_meta_box_callback',
        'post',
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'tg_notify_add_meta_box');

function tg_notify_meta_box_callback($post) {
    $value = get_post_meta($post->ID, '_tg_notify_send', true);

    // Standardmäßig auf 1 setzen, wenn der Beitrag neu ist
    if (empty($value) && get_post_status($post->ID) !== 'publish') {
        $value = 1;
    }

    wp_nonce_field('tg_notify_meta_box', 'tg_notify_meta_box_nonce');
    echo '<label><input type="checkbox" name="tg_notify_send" value="1" ' . checked($value, 1, false) . '> ' . __('Benachrichtigung senden', 'wp-stat-notice') . '</label>';
}

function tg_notify_save_post($post_id) {
    // Sicherheitsprüfungen
    if (!isset($_POST['tg_notify_meta_box_nonce']) || !wp_verify_nonce($_POST['tg_notify_meta_box_nonce'], 'tg_notify_meta_box')) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Prüfen, ob der Beitrag wirklich veröffentlicht wurde
    if (get_post_status($post_id) !== 'publish') return;

    // Prüfen, ob die Nachricht bereits gesendet wurde
    $already_sent = get_post_meta($post_id, '_tg_notify_sent', true);
    if ($already_sent) return;

    $send_notification = isset($_POST['tg_notify_send']) ? 1 : 0;
    update_post_meta($post_id, '_tg_notify_send', $send_notification);

    if ($send_notification) {
        tg_notify_send_telegram_message($post_id);
        update_post_meta($post_id, '_tg_notify_sent', 1); 
    }
}


add_action('save_post', 'tg_notify_save_post');

function tg_notify_send_telegram_message($post_id) {
    $bot_token = get_option('tg_notify_bot_token');
    $chat_ids = explode("\n", get_option('tg_notify_chat_ids'));
    $message_template = get_option('tg_notify_custom_message');

    $post = get_post($post_id);
    // Überprüfen, ob der Beitrag von einem Gast-Author stammt
    $author_name = get_the_author_meta('display_name', $post->post_author);
    if (empty($author_name)) {
        // Falls kein Name vorhanden ist (Gast-Author), den Gast-Namen verwenden oder einen Platzhalter setzen
        $author_name = 'Gast-Author';
    }

    // Nachricht formatieren
    $message = str_replace(
        ['{title}', '{author}', '{link}'],
        [$post->post_title, $author_name, get_permalink($post_id)],
        $message_template
    );

    foreach ($chat_ids as $chat_id) {
        $chat_id = trim($chat_id);
        if (!empty($chat_id)) {
            // Überprüfen, ob die ID das Thema enthält (Format: -1001234567890_123)
            if (strpos($chat_id, '_') !== false) {
                // Kanal-ID und Themen-ID trennen
                list($channel_id, $topic_id) = explode('_', $chat_id);
                $chat_id = $channel_id; 

                // Telegram API-Anfrage senden
                $url = "https://api.telegram.org/bot$bot_token/sendMessage";
                $args = [
                    'body' => json_encode([
                        'chat_id' => $chat_id,
                        'text' => $message, 
                        'parse_mode' => 'HTML',
                        'reply_to_message_id' => $topic_id 
                    ]),
                    'headers' => ['Content-Type' => 'application/json'],
                    'method' => 'POST',
                ];

                // API-Request senden und Fehlerprotokollierung
                $response = wp_remote_post($url, $args);
                if (is_wp_error($response)) {
                    $error_message = $response->get_error_message();
                    error_log("Telegram Fehler: $error_message");
                } else {
                    // Erhöhe den Telegram-Nachrichtenzähler
                    tg_notify_increment_telegram_message_count();
                    error_log('Telegram Antwort: ' . print_r($response, true));
                }
            } else {
                // Normaler Kanal ohne Thema
                $url = "https://api.telegram.org/bot$bot_token/sendMessage";
                $args = [
                    'body' => json_encode([
                        'chat_id' => $chat_id,
                        'text' => $message, 
                        'parse_mode' => 'HTML'
                    ]),
                    'headers' => ['Content-Type' => 'application/json'],
                    'method' => 'POST',
                ];

                // API-Request senden und Fehlerprotokollierung
                $response = wp_remote_post($url, $args);
                if (is_wp_error($response)) {
                    $error_message = $response->get_error_message();
                    error_log("Telegram Fehler: $error_message");
                } else {
                    // Erhöhe den Telegram-Nachrichtenzähler
                    tg_notify_increment_telegram_message_count();
                    error_log('Telegram Antwort: ' . print_r($response, true));
                }
            }
        }
    }
}

function tg_notify_increment_telegram_message_count() {
    $current_count = get_option('wp_multi_telegram_message_count', 0);
    update_option('wp_multi_telegram_message_count', $current_count + 1);
}


/*
* Admin-Dashboard Nachrichten sende Zähler
*/


// Admin Dashboard Widget für Telegram und Discord Nachrichten Zähler
function wp_multi_add_dashboard_widgets() {
    wp_add_dashboard_widget(
        'wp_multi_dashboard_widget', 
        'Telegram & Discord Nachrichten Zähler', 
        'wp_multi_display_dashboard_widget' 
    );
}
add_action('wp_dashboard_setup', 'wp_multi_add_dashboard_widgets');

// Callback-Funktion, die den Inhalt des Widgets anzeigt
function wp_multi_display_dashboard_widget() {
    // Telegram-Nachrichtenzähler
    $telegram_message_count = get_option('wp_multi_telegram_message_count', 0);
    // Discord-Nachrichtenzähler
    $discord_message_count = get_option('wp_multi_discord_message_count', 0);

    // Ausgabe der Zähler
    echo '<p><strong>Telegram Nachrichten gesendet:</strong> ' . esc_html($telegram_message_count) . '</p>';
    echo '<p><strong>Discord Nachrichten gesendet:</strong> ' . esc_html($discord_message_count) . '</p>';
}


/*
* Gast Autoren
*/

// Gast-Autor Eingabefeld in der Sidebar im Admin-Bereich hinzufügen
function wp_multi_add_guest_author_field() {
    add_meta_box(
        'guest_author_meta_box',
        __('Gast-Autor', 'wp-multi'),
        'wp_multi_guest_author_field',
        ['post', 'page', 'dein_custom_post_type'], 
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'wp_multi_add_guest_author_field');

// Callback-Funktion, die das Eingabefeld anzeigt
function wp_multi_guest_author_field($post) {
    $guest_author = get_post_meta($post->ID, '_guest_author', true);
    ?>
    <label for="guest_author"><?php _e('Gast-Autor Name:', 'wp-multi'); ?></label>
    <input type="text" id="guest_author" name="guest_author" value="<?php echo esc_attr($guest_author); ?>" class="widefat" />
    <?php
}

// Speichern der Gast-Autor Daten
function wp_multi_save_guest_author_meta($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;
    if (isset($_POST['guest_author'])) {
        $guest_author = sanitize_text_field($_POST['guest_author']);
        update_post_meta($post_id, '_guest_author', $guest_author);
    } else {
        delete_post_meta($post_id, '_guest_author');
    }
}
add_action('save_post', 'wp_multi_save_guest_author_meta');

// Gast-Autor anzeigen anstelle des regulären Autors im Frontend
function wp_multi_display_guest_author($author_name) {
    if ((is_single() || is_archive() || is_home()) && !is_admin()) {  
        $post = get_post();
        if ($post) {
            $guest_author = get_post_meta($post->ID, '_guest_author', true);
            if (!empty($guest_author)) {
                $author_name = $guest_author;
            }
        }
    }
    return $author_name;
}
add_filter('the_author', 'wp_multi_display_guest_author');

// Anzeige des Gast-Autors in der Beitragsübersicht (Backend)
function wp_multi_add_guest_author_column($columns) {
    if (isset($columns['author'])) {
        $columns['guest_author'] = __('Gast-Autor', 'wp-multi');
    }
    return $columns;
}
add_filter('manage_posts_columns', 'wp_multi_add_guest_author_column');

function wp_multi_display_guest_author_column($column_name, $post_id) {
    if ($column_name == 'guest_author') {
        $guest_author = get_post_meta($post_id, '_guest_author', true);
        echo !empty($guest_author) ? esc_html($guest_author) : __('Kein Gast-Autor', 'wp-multi');
    }
}
add_action('manage_posts_custom_column', 'wp_multi_display_guest_author_column', 10, 2);

// Admin-Menü für die Gast-Autor-Übersicht unter Benutzer hinzufügen
function wp_multi_add_guest_author_page() {
    add_submenu_page(
        'users.php',  
        __('Gast-Autor Übersicht', 'wp-multi'),     
        __('Gast-Autoren', 'wp-multi'),             
        'manage_options',                          
        'guest_author_overview',                   
        'wp_multi_guest_author_overview_page'      
    );
}
add_action('admin_menu', 'wp_multi_add_guest_author_page');

// Callback-Funktion für die Gast-Autor-Übersicht
function wp_multi_guest_author_overview_page() {
    // Sortierparameter aus URL lesen
    $orderby = isset($_GET['orderby']) ? sanitize_key($_GET['orderby']) : 'guest_author';
    $order = isset($_GET['order']) && in_array(strtoupper($_GET['order']), ['ASC', 'DESC']) ? strtoupper($_GET['order']) : 'ASC';

    // Gültige Sortierfelder
    $valid_orderby = ['guest_author' => 'pm.meta_value', 'posts' => 'post_count'];
    $sql_orderby = isset($valid_orderby[$orderby]) ? $valid_orderby[$orderby] : 'pm.meta_value';
    $sql_order = $order;

    // Basis-URL für Sortier-Links
    $base_url = add_query_arg(['page' => 'guest_author_overview'], admin_url('users.php'));

    ?>
    <div class="wrap">
        <h1><?php _e('Gast-Autor Übersicht', 'wp-multi'); ?></h1>
        <table class="wp-list-table widefat fixed striped posts">
            <thead>
                <tr>
                    <th class="column-guest_author">
                        <a href="<?php echo esc_url(add_query_arg(['orderby' => 'guest_author', 'order' => ($orderby === 'guest_author' && $order === 'ASC') ? 'DESC' : 'ASC'], $base_url)); ?>" class="<?php echo ($orderby === 'guest_author') ? 'sorted ' . strtolower($order) : 'sortable'; ?>">
                            <?php _e('Gast-Autor', 'wp-multi'); ?>
                            <?php if ($orderby === 'guest_author') : ?>
                                <span class="sorting-indicator"><?php echo ($order === 'ASC') ? '↑' : '↓'; ?></span>
                            <?php endif; ?>
                        </a>
                    </th>
                    <th class="column-posts">
                        <a href="<?php echo esc_url(add_query_arg(['orderby' => 'posts', 'order' => ($orderby === 'posts' && $order === 'ASC') ? 'DESC' : 'ASC'], $base_url)); ?>" class="<?php echo ($orderby === 'posts') ? 'sorted ' . strtolower($order) : 'sortable'; ?>">
                            <?php _e('Anzahl der Beiträge', 'wp-multi'); ?>
                            <?php if ($orderby === 'posts') : ?>
                                <span class="sorting-indicator"><?php echo ($order === 'ASC') ? '↑' : '↓'; ?></span>
                            <?php endif; ?>
                        </a>
                    </th>
                </tr>
            </thead>
            <tbody>
                <?php
                global $wpdb;
                $query = "
                    SELECT pm.meta_value AS guest_author, COUNT(*) AS post_count
                    FROM {$wpdb->posts} p
                    INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
                    WHERE pm.meta_key = '_guest_author' 
                    AND pm.meta_value != '' 
                    AND p.post_status = 'publish'
                    GROUP BY pm.meta_value
                    ORDER BY {$sql_orderby} {$sql_order}
                ";
                $guest_authors = $wpdb->get_results($query);

                

                if ($guest_authors) {
                    foreach ($guest_authors as $author) {
                        ?>
                        <tr>
                            <td><?php echo esc_html($author->guest_author); ?></td>
                            <td><?php echo esc_html($author->post_count); ?></td>
                        </tr>
                        <?php
                    }
                } else {
                    echo '<tr><td colspan="2">' . __('Keine Gast-Autoren gefunden.', 'wp-multi') . '</td></tr>';
                }
                ?>
            </tbody>
        </table>
    </div>
    <?php
}

// Schönes CSS nur für die Gast-Autor-Übersicht
function wp_multi_guest_author_overview_css() {
    if (isset($_GET['page']) && $_GET['page'] == 'guest_author_overview') {
        ?>
        <style>
    .wrap {
        background-color: #ffffff;
        padding: 24px;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        margin: 20px 20px 20px 0;
        max-width: 1200px;
    }

    .wrap h1 {
        font-size: 28px;
        font-weight: 600;
        color: #1a1a1a;
        margin-bottom: 24px;
        line-height: 1.3;
    }

    .wp-list-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        background-color: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }

    .wp-list-table th, .wp-list-table td {
        padding: 16px;
        font-size: 14px;
        color: #374151;
        border-bottom: 1px solid #e5e7eb;
        text-align: left; /* Standard Textausrichtung */
    }

    /* Kopfzeilen und Datenzellen der Spalte 'posts' zentrieren */
    .wp-list-table th.column-posts, .wp-list-table td.column-posts {
        text-align: center !important;   /* !important stellt sicher, dass diese Regel Vorrang hat */
        vertical-align: middle !important;  /* Vertikal mittig ausrichten mit !important */
        width: 200px !important;         /* Kann je nach Bedarf angepasst werden */
    }

    /* Optional: Wenn du sicherstellen möchtest, dass auch die Kopfzeile mit einer festen Breite arbeitet */
    .wp-list-table th.column-posts {
        width: 200px !important;         /* Breite der Kopfzeile mit !important */
    }

    .wp-list-table th.column-guest_author {
        width: auto;
    }

    .wp-list-table th {
        background-color: #f8fafc;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #1f2937;
    }

    .wp-list-table tr:last-child td {
        border-bottom: none;
    }

    .wp-list-table tr:nth-child(even) {
        background-color: #f9fafb;
    }

    .wp-list-table th a {
        text-decoration: none;
        color: #2563eb;
        display: inline-flex;
        align-items: center;
        transition: color 0.2s ease;
        font-weight: 600;
    }

    .wp-list-table th a:hover {
        color: #1d4ed8;
        text-decoration: underline;
    }

    .wp-list-table th a:focus {
        outline: none;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.3);
        border-radius: 4px;
    }

    .wp-list-table th.sorted a {
        color: #111827;
        font-weight: 700;
    }

    .wp-list-table th .sorting-indicator {
        margin-left: 8px;
        font-size: 12px;
        color: #6b7280;
        transition: color 0.2s ease;
    }

    .wp-list-table th.sorted .sorting-indicator {
        color: #111827;
    }

    .wp-list-table th.sortable a:hover .sorting-indicator {
        color: #1d4ed8;
    }

    .wp-list-table td {
        vertical-align: middle;
    }

    @media (max-width: 768px) {
        .wp-list-table th, .wp-list-table td {
            padding: 12px;
            font-size: 13px;
        }

        .wp-list-table th.column-posts {
            width: 100px;
        }

        .wrap h1 {
            font-size: 24px;
        }
    }
</style>


        <?php
    }
}
add_action('admin_head', 'wp_multi_guest_author_overview_css');

// Funktion zum Erstellen der Gastautoren-Beitragsseite
function wp_multi_create_guest_author_page() {
    $page_title = __('Gastautor Beiträge', 'wp-multi');
    $page_slug = 'gastautor-beitraege';
    $page = get_page_by_path($page_slug);

    if (!$page) {
        $page_id = wp_insert_post(array(
            'post_title' => $page_title,
            'post_name' => $page_slug,
            'post_content' => '[guest_author_posts]',
            'post_status' => 'publish',
            'post_type' => 'page',
        ));

        if ($page_id && !is_wp_error($page_id)) {
            update_option('wp_multi_guest_author_page_id', $page_id);
        }
    } else {
        update_option('wp_multi_guest_author_page_id', $page->ID);
    }
}
add_action('init', 'wp_multi_create_guest_author_page');

// Shortcode für Gastautoren-Liste
function wp_multi_guest_author_shortcode() {
    ob_start();
    global $wpdb;

    // Alle Gastautoren mit Beitragsanzahl abrufen
    $query = "
        SELECT pm.meta_value AS guest_author, COUNT(*) AS post_count
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
        WHERE pm.meta_key = '_guest_author' 
        AND pm.meta_value != '' 
        AND p.post_status = 'publish'
        GROUP BY pm.meta_value
        ORDER BY pm.meta_value ASC
    ";
    $guest_authors = $wpdb->get_results($query);

    // URL der Gastautoren-Beitragsseite
    $guest_author_page_id = get_option('wp_multi_guest_author_page_id');
    $guest_author_page_url = $guest_author_page_id ? get_permalink($guest_author_page_id) : '#';

    ?>
    <div id="guest-author-section" class="container mx-auto px-4 py-8">
        <!-- Gastautoren-Liste -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <?php if ($guest_authors) : ?>
                <?php foreach ($guest_authors as $author) : ?>
                    <a href="<?php echo esc_url(add_query_arg('guest_author', urlencode($author->guest_author), $guest_author_page_url)); ?>" class="guest-author-card bg-white p-6 rounded-lg shadow-md hover:shadow-lg transition">
                        <h3 class="text-xl font-semibold text-gray-800"><?php echo esc_html($author->guest_author); ?></h3>
                        <p class="text-gray-600"><?php echo esc_html($author->post_count); ?> <?php _e('Beiträge', 'wp-multi'); ?></p>
                    </a>
                <?php endforeach; ?>
            <?php else : ?>
                <p class="col-span-2 text-center text-gray-600"><?php _e('Keine Gastautoren gefunden.', 'wp-multi'); ?></p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <?php

    return ob_get_clean();
}
add_shortcode('guest_authors', 'wp_multi_guest_author_shortcode');

// Shortcode für Gastautoren-Beiträge
function wp_multi_guest_author_posts_shortcode() {
    ob_start();

    $guest_author = isset($_GET['guest_author']) ? sanitize_text_field(urldecode($_GET['guest_author'])) : '';

    ?>
    <div id="guest-author-posts" class="container mx-auto px-4 py-8">
        <h2 class="text-2xl font-semibold text-gray-800 mb-4">
            <?php
            if ($guest_author) {
                printf(__('Beiträge von %s', 'wp-multi'), esc_html($guest_author));
            } else {
                _e('Beiträge auswählen', 'wp-multi');
            }
            ?>
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <?php
            if ($guest_author) {
                // Überprüfen, ob die Kategorie "series" existiert
                $series_category = term_exists('series', 'category');
                $debug_message = '';

                if (!$series_category) {
                    $debug_message = '<p class="col-span-2 text-red-600">Debug: Kategorie mit Slug "series" wurde nicht gefunden. Bitte überprüfe den Kategorie-Slug.</p>';
                }

                $args = array(
                    'post_type' => ['post', 'page', 'dein_custom_post_type'],
                    'post_status' => 'publish',
                    'meta_query' => array(
                        array(
                            'key' => '_guest_author',
                            'value' => $guest_author,
                            'compare' => '='
                        )
                    ),
                    'tax_query' => array(
                        array(
                            'taxonomy' => 'category',
                            'field' => 'slug',
                            'terms' => 'series',
                            'operator' => 'NOT IN'
                        )
                    ),
                    'posts_per_page' => -1
                );

                $query = new WP_Query($args);

                

                if ($query->have_posts()) {
                    while ($query->have_posts()) {
                        $query->the_post();
                        // Beitragsinhalt abrufen und kürzen
                        $content = get_the_content();
                        $content = wp_strip_all_tags($content); // HTML-Tags entfernen
                        $trimmed_content = wp_trim_words($content, 30, '...');
                        ?>
                        <div class="post-card bg-white p-6 rounded-lg shadow-md">
                            <h3 class="text-lg font-medium text-gray-800">
                                <a href="<?php the_permalink(); ?>" class="hover:text-blue-600"><?php the_title(); ?></a>
                            </h3>
                            <p class="text-gray-600 line-clamp-3"><?php echo esc_html($trimmed_content); ?></p>
                        </div>
                        <?php
                    }
                    wp_reset_postdata();
                } else {
                    ?>
                    <p class="col-span-2 text-gray-600"><?php _e('Keine Beiträge gefunden.', 'wp-multi'); ?></p>
                    <?php
                }
            } else {
                ?>
                <p class="col-span-2 text-gray-600"><?php _e('Wählen Sie einen Gastautor aus, um die Beiträge anzuzeigen.', 'wp-multi'); ?></p>
                <?php
            }
            ?>
        </div>
    </div>

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <?php

    return ob_get_clean();
}
add_shortcode('guest_author_posts', 'wp_multi_guest_author_posts_shortcode');

/*
 * Custom Text Box
 */

// Funktion zur Registrierung der zusätzlichen Einstellungen für benutzerdefinierte Texte
function wp_multi_custom_text_register_settings() {
    add_option('wp_multi_custom_texts', '');
    add_option('wp_multi_second_custom_text', '');
    add_option('wp_multi_enable_custom_texts', '1');
    register_setting('wp_multi_custom_text_options_group', 'wp_multi_custom_texts');
    register_setting('wp_multi_custom_text_options_group', 'wp_multi_second_custom_text');
    register_setting('wp_multi_custom_text_options_group', 'wp_multi_enable_custom_texts');
}
add_action('admin_init', 'wp_multi_custom_text_register_settings');

// Funktion zum Hinzufügen des Menüeintrags unter "Beiträge"
function wp_multi_custom_text_add_settings_page() {
    add_submenu_page(
        'edit.php',
        __('WP Multi Custom Text Einstellungen', 'wp-multi'),
        __('Custom Text Einstellungen', 'wp-multi'),
        'manage_options',
        'wp_multi_custom_text_settings',
        'wp_multi_custom_text_settings_page_content'
    );
}
add_action('admin_menu', 'wp_multi_custom_text_add_settings_page');

// Funktion zum Erstellen der Einstellungsseite
function wp_multi_custom_text_settings_page_content() {
    ?>
    <div class="wrap">
        <div class="wp-multi-header-box">
            <div class="wp-multi-banner">
                <img src="https://m-viper.de/img/logo.png" alt="M_Viper Logo" class="wp-multi-logo" />
                <h1>Custom Text verwalten</h1>
            </div>
        </div>
        <form method="post" action="options.php">
            <?php settings_fields('wp_multi_custom_text_options_group'); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><?php _e('Custom Texte aktivieren', 'wp-multi'); ?></th>
                    <td>
                        <input type="checkbox" name="wp_multi_enable_custom_texts" value="1" <?php checked(1, get_option('wp_multi_enable_custom_texts'), true); ?> />
                        <p class="description"><?php _e('Aktiviere oder deaktiviere die Anzeige der benutzerdefinierten Texte auf der Webseite.', 'wp-multi'); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php _e('Custom Texte', 'wp-multi'); ?></th>
                    <td>
                        <textarea name="wp_multi_custom_texts" rows="10" cols="50" class="large-text"><?php echo esc_textarea(get_option('wp_multi_custom_texts')); ?></textarea>
                        <p class="description"><?php _e('Gib jeden Text in einer neuen Zeile ein.', 'wp-multi'); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php _e('Zweiter Custom Text', 'wp-multi'); ?></th>
                    <td>
                        <textarea name="wp_multi_second_custom_text" rows="10" cols="50" class="large-text"><?php echo esc_textarea(get_option('wp_multi_second_custom_text')); ?></textarea>
                        <p class="description"><?php _e('Gib den zweiten Custom Text ein, der über der ersten Box angezeigt wird.', 'wp-multi'); ?></p>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <style>
        .wp-multi-header-box {
            text-align: center;
            margin-top: 20px;
            padding: 20px;
            background-color: #f1f1f1;
        }
        .wp-multi-logo {
            max-height: 80px;
        }
        .wp-multi-banner {
            background-color: #0073aa;
            padding: 10px;
            text-align: center;
            margin-top: 20px;
        }
        .wp-multi-banner h1 {
            font-size: 30px;
            margin: 0;
            font-weight: 600;
        }
        .form-table {
            margin-top: 30px;
        }
        .form-table th {
            width: 220px;
            font-weight: bold;
        }
        .form-table td {
            width: auto;
        }
        .wp-multi-table input, .wp-multi-table textarea {
            width: 100%;
            border-radius: 5px;
            padding: 10px;
            border: 1px solid #ccc;
        }
        .wp-multi-table input:focus, .wp-multi-table textarea:focus {
            border-color: #0073aa;
        }
        .button-primary {
            background-color: #0073aa;
            border-color: #0073aa;
        }
        .button-primary:hover {
            background-color: #005f8d;
            border-color: #005f8d;
        }
    </style>
    <?php
}

// Anzeige der Custom Texts in einer Box im Frontend
function wp_multi_custom_text_display($content) {
    $enable_custom_texts = get_option('wp_multi_enable_custom_texts', '1');
    if ($enable_custom_texts !== '1') {
        return $content;
    }

    if (is_single()) {
        global $post;
        $guest_author_name = get_post_meta($post->ID, 'guest_author', true);
        $author_name = !empty($guest_author_name) ? $guest_author_name : get_the_author();
        $custom_texts = get_option('wp_multi_custom_texts', '');
        $second_custom_texts = get_option('wp_multi_second_custom_text', '');
        $custom_texts_array = array_filter(array_map('trim', explode("\n", $custom_texts)));
        $second_custom_texts_array = array_filter(array_map('trim', explode("\n", $second_custom_texts)));
        $selected_custom_text = get_post_meta($post->ID, '_custom_text_choice', true);
        $selected_second_custom_text = get_post_meta($post->ID, '_second_custom_text_choice', true);

        if (empty($custom_texts_array) && empty($second_custom_texts_array)) {
            return $content;
        }

        $output = '<div class="custom-text-box" style="margin-top: 40px; padding: 20px; background-color: #f0f0f0; border: 2px solid #ddd; border-radius: 10px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); max-width: 400px; width: auto; font-size: 16px; line-height: 1.2; clear: both; margin-left: auto; margin-right: 0; display: block; margin-bottom: 20px; position: relative;">';
        $output .= '<p><strong>' . __('Autor:', 'wp-multi') . ' ' . esc_html($author_name);
        if ($selected_second_custom_text !== '' && isset($second_custom_texts_array[$selected_second_custom_text])) {
            $output .= '  |  ' . esc_html($second_custom_texts_array[$selected_second_custom_text]);
        }
        $output .= '</strong></p>';
        if ($selected_custom_text !== '' && isset($custom_texts_array[$selected_custom_text])) {
            $output .= '<p><em>' . esc_html($custom_texts_array[$selected_custom_text]) . '</em></p>';
        }
        $output .= '</div>';

        return $content . $output;
    }
    return $content;
}
add_filter('the_content', 'wp_multi_custom_text_display');

// Funktion zum Hinzufügen der Meta-Box für beide Custom Texts
function wp_multi_add_custom_text_fields($post) {
    $custom_texts = get_option('wp_multi_custom_texts');
    $custom_texts_array = array_filter(array_map('trim', explode("\n", $custom_texts)));
    $second_custom_text = get_option('wp_multi_second_custom_text');
    $second_custom_text_array = array_filter(array_map('trim', explode("\n", $second_custom_text)));
    $selected_custom_text = get_post_meta($post->ID, '_custom_text_choice', true);
    $selected_second_custom_text = get_post_meta($post->ID, '_second_custom_text_choice', true);
    ?>
    <label for="custom_text_choice"><?php _e('Wähle den Custom Text (unterer Bereich):', 'wp-multi'); ?></label>
    <select name="custom_text_choice" id="custom_text_choice" class="widefat">
        <option value=""><?php _e('Keinen Text auswählen', 'wp-multi'); ?></option>
        <?php foreach ($custom_texts_array as $key => $value) { ?>
            <option value="<?php echo esc_attr($key); ?>" <?php selected($selected_custom_text, $key); ?>><?php echo esc_html($value); ?></option>
        <?php } ?>
    </select>
    <label for="second_custom_text_choice"><?php _e('Wähle den zweiten Custom Text (oberer Bereich):', 'wp-multi'); ?></label>
    <select name="second_custom_text_choice" id="second_custom_text_choice" class="widefat">
        <option value=""><?php _e('Keinen Text auswählen', 'wp-multi'); ?></option>
        <?php foreach ($second_custom_text_array as $key => $value) { ?>
            <option value="<?php echo esc_attr($key); ?>" <?php selected($selected_second_custom_text, $key); ?>><?php echo esc_html($value); ?></option>
        <?php } ?>
    </select>
    <?php
}

// Meta-Box hinzufügen
add_action('add_meta_boxes', function() {
    add_meta_box('wp_multi_custom_text', __('Custom Text Auswahl', 'wp-multi'), 'wp_multi_add_custom_text_fields', 'post', 'normal', 'high');
});

// Speichern der benutzerdefinierten Textauswahl im Beitrag
function wp_multi_save_custom_text_choice($post_id) {
    if (isset($_POST['custom_text_choice'])) {
        update_post_meta($post_id, '_custom_text_choice', sanitize_text_field($_POST['custom_text_choice']));
    }
    if (isset($_POST['second_custom_text_choice'])) {
        update_post_meta($post_id, '_second_custom_text_choice', sanitize_text_field($_POST['second_custom_text_choice']));
    }
}
add_action('save_post', 'wp_multi_save_custom_text_choice');

/*
* Custom Link im Admin Sidebar hinzufügen
*/


// Funktion zum Hinzufügen des benutzerdefinierten Menüs
function wp_stat_notice_add_custom_pages() {
    $custom_pages = get_option('wp_stat_notice_custom_pages', []);

    if (!empty($custom_pages) && is_array($custom_pages)) {
        foreach ($custom_pages as $page) {
            if (!isset($page['title'], $page['slug'], $page['icon'])) {
                continue; // Überspringe ungültige Einträge
            }

            add_menu_page(
                $page['title'],
                $page['title'],
                'manage_options',
                $page['slug'],
                'wp_stat_notice_custom_page',
                $page['icon'] ?: 'dashicons-admin-links', // Fallback-Icon
                100
            );
        }
    }
}
add_action('admin_menu', 'wp_stat_notice_add_custom_pages');

// Callback-Funktion für das Anzeigen der benutzerdefinierten Seiten
function wp_stat_notice_custom_page() {
    $current_slug = isset($_GET['page']) ? sanitize_key($_GET['page']) : '';
    $custom_pages = get_option('wp_stat_notice_custom_pages', []);

    if (empty($custom_pages) || !is_array($custom_pages)) {
        echo '<div class="notice notice-error"><p>' . __('Keine benutzerdefinierten Seiten gefunden.', 'wp-stat-notice') . '</p></div>';
        return;
    }

    foreach ($custom_pages as $page) {
        if ($page['slug'] === $current_slug) {
            if (isset($page['url']) && filter_var($page['url'], FILTER_VALIDATE_URL)) {
                // Externe URL in neuem Fenster öffnen
                echo '<script>window.open("' . esc_url($page['url']) . '", "_blank");</script>';
                echo '<div class="wrap"><h1>' . esc_html($page['title']) . '</h1>';
                echo '<p>' . __('Die externe Seite wird in einem neuen Fenster geöffnet.', 'wp-stat-notice') . '</p></div>';
            } else {
                // Interne Seite anzeigen
                echo '<div class="wrap"><h1>' . esc_html($page['title']) . '</h1>';
                echo '<p>' . __('Dies ist eine benutzerdefinierte Seite im Admin-Bereich.', 'wp-stat-notice') . '</p></div>';
            }
            return;
        }
    }

    echo '<div class="notice notice-error"><p>' . __('Seite nicht gefunden.', 'wp-stat-notice') . '</p></div>';
}

// Funktion zum Hinzufügen und Verwalten benutzerdefinierter Seiten
function wp_stat_notice_add_custom_page_form() {
    $dashicons = [
        'dashicons-admin-links', 'dashicons-admin-site', 'dashicons-admin-home',
        'dashicons-admin-plugins', 'dashicons-admin-users', 'dashicons-analytics',
        'dashicons-archive', 'dashicons-book', 'dashicons-calendar',
        'dashicons-camera', 'dashicons-cart', 'dashicons-cloud',
        'dashicons-clipboard', 'dashicons-clock', 'dashicons-cloud-upload',
        'dashicons-email', 'dashicons-heart', 'dashicons-laptop',
        'dashicons-lock', 'dashicons-phone', 'dashicons-rss',
        'dashicons-search', 'dashicons-settings', 'dashicons-share',
        'dashicons-tag', 'dashicons-thumbs-up', 'dashicons-welcome-learn-more',
        'dashicons-welcome-write-blog'
    ];

    ?>
    <div class="wrap">
        <h1><?php _e('Benutzerdefinierten Adminlink hinzufügen', 'wp-stat-notice'); ?></h1>

        <!-- Formular zum Hinzufügen -->
        <form method="post" action="">
            <?php wp_nonce_field('wp_stat_notice_add_page', 'wp_stat_notice_nonce'); ?>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="page_title"><?php _e('Titel der Seite', 'wp-stat-notice'); ?></label></th>
                    <td><input type="text" name="page_title" id="page_title" required class="regular-text"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="page_url"><?php _e('URL der Seite (optional)', 'wp-stat-notice'); ?></label></th>
                    <td><input type="url" name="page_url" id="page_url" class="regular-text" placeholder="https://example.com"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="page_slug"><?php _e('Slug der Seite', 'wp-stat-notice'); ?></label></th>
                    <td><input type="text" name="page_slug" id="page_slug" required class="regular-text"></td>
                </tr>
                <tr>
                    <th scope="row"><label for="page_icon"><?php _e('Dashicon auswählen', 'wp-stat-notice'); ?></label></th>
                    <td>
                        <select name="page_icon" id="page_icon" onchange="updateIconPreview()">
                            <?php foreach ($dashicons as $dashicon): ?>
                                <option value="<?php echo esc_attr($dashicon); ?>"><?php echo esc_html($dashicon); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div id="icon-preview" class="dashicons" style="font-size: 24px; margin-top: 10px;"></div>
                    </td>
                </tr>
            </table>
            <p><input type="submit" name="add_custom_page" class="button button-primary" value="<?php _e('Seite hinzufügen', 'wp-stat-notice'); ?>"></p>
        </form>

        <?php
        // Formularverarbeitung für Hinzufügen
        if (isset($_POST['add_custom_page']) && check_admin_referer('wp_stat_notice_add_page', 'wp_stat_notice_nonce')) {
            $title = sanitize_text_field($_POST['page_title']);
            $url = !empty($_POST['page_url']) ? esc_url_raw($_POST['page_url']) : '';
            $slug = sanitize_key($_POST['page_slug']);
            $icon = in_array($_POST['page_icon'], $dashicons) ? $_POST['page_icon'] : 'dashicons-admin-links';

            if (empty($title) || empty($slug)) {
                echo '<div class="notice notice-error"><p>' . __('Titel und Slug sind erforderlich.', 'wp-stat-notice') . '</p></div>';
            } else {
                $custom_pages = get_option('wp_stat_notice_custom_pages', []);
                $slugs = array_column($custom_pages, 'slug');
                if (in_array($slug, $slugs)) {
                    echo '<div class="notice notice-error"><p>' . __('Dieser Slug wird bereits verwendet.', 'wp-stat-notice') . '</p></div>';
                } else {
                    $custom_pages[] = ['title' => $title, 'url' => $url, 'slug' => $slug, 'icon' => $icon];
                    update_option('wp_stat_notice_custom_pages', $custom_pages);
                    echo '<div class="updated"><p>' . __('Benutzerdefinierte Seite wurde hinzugefügt!', 'wp-stat-notice') . '</p></div>';
                }
            }
        }

        // Verwaltung der Seiten
        $custom_pages = get_option('wp_stat_notice_custom_pages', []);
        if (!empty($custom_pages)) {
            echo '<h2>' . __('Verwaltung der benutzerdefinierten Seiten', 'wp-stat-notice') . '</h2>';
            echo '<table class="widefat fixed" cellspacing="0">';
            echo '<thead><tr><th>' . __('Titel', 'wp-stat-notice') . '</th><th>' . __('URL', 'wp-stat-notice') . '</th><th>' . __('Slug', 'wp-stat-notice') . '</th><th>' . __('Aktionen', 'wp-stat-notice') . '</th></tr></thead>';
            echo '<tbody>';
            foreach ($custom_pages as $index => $page) {
                echo '<tr>';
                echo '<td>' . esc_html($page['title']) . '</td>';
                echo '<td>' . esc_html($page['url'] ?: '-') . '</td>';
                echo '<td>' . esc_html($page['slug']) . '</td>';
                echo '<td><a href="' . admin_url('admin.php?page=wp-stat-notice-custom-page&edit=' . $index) . '">' . __('Bearbeiten', 'wp-stat-notice') . '</a> | ';
                echo '<a href="' . admin_url('admin.php?page=wp-stat-notice-custom-page&delete=' . $index) . '" onclick="return confirm(\'' . __('Möchtest du diese Seite wirklich löschen?', 'wp-stat-notice') . '\')">' . __('Löschen', 'wp-stat-notice') . '</a></td>';
                echo '</tr>';
            }
            echo '</tbody></table>';
        }

        // Bearbeiten
        if (isset($_GET['edit']) && isset($custom_pages[$_GET['edit']])) {
            $edit_index = (int)$_GET['edit'];
            $edit_page = $custom_pages[$edit_index];

            echo '<h2>' . __('Seite bearbeiten', 'wp-stat-notice') . '</h2>';
            ?>
            <form method="post" action="">
                <?php wp_nonce_field('wp_stat_notice_edit_page', 'wp_stat_notice_nonce'); ?>
                <table class="form-table">
                    <tr>
                        <th scope="row"><label for="edit_page_title"><?php _e('Titel der Seite', 'wp-stat-notice'); ?></label></th>
                        <td><input type="text" name="edit_page_title" id="edit_page_title" value="<?php echo esc_attr($edit_page['title']); ?>" required class="regular-text"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="edit_page_url"><?php _e('URL der Seite (optional)', 'wp-stat-notice'); ?></label></th>
                        <td><input type="url" name="edit_page_url" id="edit_page_url" value="<?php echo esc_attr($edit_page['url']); ?>" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="edit_page_slug"><?php _e('Slug der Seite', 'wp-stat-notice'); ?></label></th>
                        <td><input type="text" name="edit_page_slug" id="edit_page_slug" value="<?php echo esc_attr($edit_page['slug']); ?>" required class="regular-text"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="edit_page_icon"><?php _e('Dashicon', 'wp-stat-notice'); ?></label></th>
                        <td>
                            <select name="edit_page_icon" id="edit_page_icon" onchange="updateIconPreview()">
                                <?php foreach ($dashicons as $dashicon): ?>
                                    <option value="<?php echo esc_attr($dashicon); ?>" <?php selected($edit_page['icon'], $dashicon); ?>><?php echo esc_html($dashicon); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div id="icon-preview" class="dashicons <?php echo esc_attr($edit_page['icon']); ?>" style="font-size: 24px; margin-top: 10px;"></div>
                        </td>
                    </tr>
                </table>
                <p><input type="submit" name="save_custom_page" class="button button-primary" value="<?php _e('Änderungen speichern', 'wp-stat-notice'); ?>"></p>
            </form>
            <?php

            if (isset($_POST['save_custom_page']) && check_admin_referer('wp_stat_notice_edit_page', 'wp_stat_notice_nonce')) {
                $title = sanitize_text_field($_POST['edit_page_title']);
                $url = !empty($_POST['edit_page_url']) ? esc_url_raw($_POST['edit_page_url']) : '';
                $slug = sanitize_key($_POST['edit_page_slug']);
                $icon = in_array($_POST['edit_page_icon'], $dashicons) ? $_POST['edit_page_icon'] : 'dashicons-admin-links';

                if (empty($title) || empty($slug)) {
                    echo '<div class="notice notice-error"><p>' . __('Titel und Slug sind erforderlich.', 'wp-stat-notice') . '</p></div>';
                } else {
                    $custom_pages[$edit_index] = ['title' => $title, 'url' => $url, 'slug' => $slug, 'icon' => $icon];
                    update_option('wp_stat_notice_custom_pages', $custom_pages);
                    echo '<div class="updated"><p>' . __('Seite erfolgreich bearbeitet!', 'wp-stat-notice') . '</p></div>';
                }
            }
        }

        // Löschen
        if (isset($_GET['delete']) && isset($custom_pages[$_GET['delete']])) {
            $delete_index = (int)$_GET['delete'];
            unset($custom_pages[$delete_index]);
            $custom_pages = array_values($custom_pages);
            update_option('wp_stat_notice_custom_pages', $custom_pages);
            echo '<div class="updated"><p>' . __('Seite wurde gelöscht.', 'wp-stat-notice') . '</p></div>';
        }
        ?>
    </div>

    <script>
    function updateIconPreview() {
        const select = document.getElementById(event.target.id);
        const preview = select.nextElementSibling;
        preview.className = 'dashicons ' + select.value;
    }
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('#page_icon, #edit_page_icon').forEach(select => {
            updateIconPreview({target: select});
        });
    });
    </script>
    <?php
}

// Untermenüpunkt hinzufügen
function wp_stat_notice_custom_page_add_form() {
    add_submenu_page(
        'tools.php',
        __('Admin-Link hinzufügen', 'wp-stat-notice'),
        __('Admin-Link hinzufügen', 'wp-stat-notice'),
        'manage_options',
        'wp-stat-notice-custom-page',
        'wp_stat_notice_add_custom_page_form'
    );
}
add_action('admin_menu', 'wp_stat_notice_custom_page_add_form');


/*
* Beitrags Report
*/


// Funktion zum Erstellen und Aktualisieren der Datenbanktabelle für gemeldete Beiträge
function wp_stat_notice_create_reported_posts_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'reported_posts';
    $charset_collate = $wpdb->get_charset_collate();

    // SQL für die Tabelle
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        post_id BIGINT(20) NOT NULL,
        report_date DATETIME DEFAULT CURRENT_TIMESTAMP,
        reason TEXT NOT NULL,
        name VARCHAR(255) NOT NULL,
        status VARCHAR(20) DEFAULT 'reported',
        user_id BIGINT(20) UNSIGNED DEFAULT NULL,
        PRIMARY KEY (id),
        KEY post_id (post_id),
        KEY user_id (user_id)
    ) $charset_collate;";

    // Zuerst prüfen, ob die Spalte `name` vorhanden ist
    $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");

    $column_names = array_map(function($column) {
        return $column->Field;
    }, $columns);

    // Wenn die Spalte 'name' nicht vorhanden ist, wird sie hinzugefügt
    if (!in_array('name', $column_names)) {
        $wpdb->query("ALTER TABLE $table_name ADD COLUMN `name` VARCHAR(255) NOT NULL");
    }

    // Tabelle erstellen oder aktualisieren
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql); 
}

register_activation_hook(__FILE__, 'wp_stat_notice_create_reported_posts_table');


// Shortcode für den "Beitrag melden"-Button
function wp_stat_notice_report_button($atts) {
    global $post;
    if (!is_user_logged_in()) return ''; 

    $atts = shortcode_atts(array('post_id' => $post->ID), $atts, 'report_button');
    $nonce = wp_create_nonce('report_post_nonce');

    // Report-Button & Eingabefelder für Name und Grund
    ob_start();
    ?>
    <button class="report-post" data-post-id="<?php echo esc_attr($atts['post_id']); ?>" data-nonce="<?php echo esc_attr($nonce); ?>">
        Beitrag melden
    </button>
    <div class="report-reason" style="display:none;">
        <input type="text" class="report-name" placeholder="Geben Sie Ihren Namen an" required />
        <textarea class="report-reason-text" placeholder="Geben Sie den Grund an" required></textarea>
        <button class="submit-report">Bericht absenden</button>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('report_button', 'wp_stat_notice_report_button');

// Stil für das Meldeformular
function wp_stat_notice_report_button_styles() {
    ?>
    <style>
        .report-reason {
            display: none;
            margin-top: 10px;
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            width: 300px;
            margin-top: 10px;
        }
        .report-reason input, .report-reason textarea {
            width: 100%;
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .report-reason button {
            background-color: #0073aa;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .report-reason button:hover {
            background-color: #005177;
        }
        .report-post {
            background-color: #ff7f00;
            color: white;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
        .report-post:hover {
            background-color: #e07b00;
        }
    </style>
    <?php
}
add_action('wp_head', 'wp_stat_notice_report_button_styles');

// Dashboard-Widget hinzufügen
function wp_stat_notice_add_dashboard_widget() {
    wp_add_dashboard_widget(
        'wp_stat_notice_dashboard_widget', 
        'Letzte 10 gemeldete Beiträge',    
        'wp_stat_notice_dashboard_widget_display' 
    );
}
add_action('wp_dashboard_setup', 'wp_stat_notice_add_dashboard_widget');

// Funktion, die das Dashboard-Widget anzeigt
function wp_stat_notice_dashboard_widget_display() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'reported_posts';

    // Abfrage, um die letzten 10 gemeldeten Beiträge zu holen
    $reports = $wpdb->get_results(
        "SELECT * FROM $table_name ORDER BY report_date DESC LIMIT 10"
    );

    if (empty($reports)) {
        echo '<p>Es gibt keine gemeldeten Beiträge.</p>';
        return;
    }

    // Tabelle mit den letzten 10 gemeldeten Beiträgen anzeigen
    echo '<table class="wp-list-table widefat fixed striped">';
    echo '<thead><tr><th>Beitrag</th><th>Datum</th><th>Grund</th></tr></thead><tbody>';

    foreach ($reports as $report) {
        $post = get_post($report->post_id);
        echo '<tr>';
        echo '<td>' . esc_html($post->post_title) . '</td>';
        echo '<td>' . esc_html($report->report_date) . '</td>';
        echo '<td>' . esc_html($report->reason) . '</td>';
        echo '</tr>';
    }

    echo '</tbody></table>';
}

// AJAX-Handler zum Senden eines Reports
function wp_stat_notice_handle_report() {
    check_ajax_referer('report_post_nonce', 'nonce');

    if (!isset($_POST['post_id'], $_POST['reason'], $_POST['name']) || !is_user_logged_in()) {
        wp_send_json_error(array('message' => 'Ungültige Anfrage.'));
        return;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'reported_posts';

    $post_id = intval($_POST['post_id']);
    $reason = sanitize_textarea_field($_POST['reason']);
    $name = sanitize_text_field($_POST['name']);
    $user_id = get_current_user_id();

    // Versuche den Eintrag in die Datenbank zu schreiben
    $result = $wpdb->insert(
        $table_name,
        array(
            'post_id'     => $post_id,
            'reason'      => $reason,
            'name'        => $name,
            'status'      => 'reported',
            'user_id'     => $user_id
        ),
        array('%d', '%s', '%s', '%s', '%d') 
    );

    if ($result === false) {
        error_log("Datenbankfehler: " . $wpdb->last_error); // WP Debug Log
        wp_send_json_error(array('message' => 'Datenbankfehler: ' . $wpdb->last_error));
    } else {
        wp_send_json_success(array('message' => 'Bericht erfolgreich gesendet.'));
    }
}
add_action('wp_ajax_report_post', 'wp_stat_notice_handle_report');


// JavaScript in den Footer einfügen
function wp_stat_notice_inline_js() {
    ?>
    <script>
jQuery(document).ready(function ($) {
    $(document).on("click", ".report-post", function () {
        let reasonBox = $(this).next(".report-reason");
        reasonBox.toggle();
    });

    $(document).on("click", ".submit-report", function () {
        let button = $(this);
        let container = button.closest(".report-reason");
        let reason = container.find(".report-reason-text").val();
        let name = container.find(".report-name").val();
        let postId = button.closest(".report-reason").prev(".report-post").data("post-id");
        let nonce = button.closest(".report-reason").prev(".report-post").data("nonce");

        if (!reason || !name) {
            alert("Bitte geben Sie sowohl Ihren Namen als auch einen Grund an.");
            return;
        }

        $.ajax({
            url: "<?php echo admin_url('admin-ajax.php'); ?>",
            type: "POST",
            data: {
                action: "report_post",
                post_id: postId,
                reason: reason,
                name: name,
                nonce: nonce
            },
            success: function (response) {
                if (response.success) {
                    alert("Der Bericht wurde erfolgreich gesendet.");
                    container.hide();
                } else {
                    alert("Fehler: " + response.data.message);
                }
            }
        });
    });
});
</script>

    <?php
}
add_action('wp_footer', 'wp_stat_notice_inline_js');

// Admin-Seite für gemeldete Beiträge
function wp_stat_notice_reported_posts_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'reported_posts';
    $reports = $wpdb->get_results("SELECT * FROM $table_name ORDER BY report_date DESC");

    ?>
    <div class="wrap">
        <h1><?php _e('Gemeldete Beiträge', 'wp-stat-notice'); ?></h1>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>Beitrag</th>
                    <th>Datum</th>
                    <th>Name</th>
                    <th>Grund</th>
                    <th>Status</th>
                    <th>Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($reports as $report): 
                    $post = get_post($report->post_id); ?>
                    <tr>
                        <td><?php echo esc_html($post->post_title); ?></td>
                        <td><?php echo esc_html($report->report_date); ?></td>
                        <td><?php echo esc_html($report->name); ?></td>
                        <td><?php echo esc_html($report->reason); ?></td>
                        <td><?php echo esc_html($report->status); ?></td>
                        <td>
                            <a href="?page=reported-posts&delete_report=<?php echo esc_attr($report->id); ?>" class="delete-report">Report Löschen</a> |
                            <a href="?page=reported-posts&unpublish_report=<?php echo esc_attr($report->id); ?>" class="unpublish-report">Unpublish</a> |
                            <a href="?page=reported-posts&delete_post=<?php echo esc_attr($report->post_id); ?>" class="delete-post">Beitrag Löschen</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
}

// Aktionen für Report-Handling
function wp_stat_notice_handle_report_actions() {
    global $wpdb;
    if (isset($_GET['delete_report'])) {
        $wpdb->delete($wpdb->prefix . 'reported_posts', array('id' => intval($_GET['delete_report'])));
    } elseif (isset($_GET['unpublish_report'])) {
        $wpdb->update($wpdb->prefix . 'reported_posts', array('status' => 'unpublished'), array('id' => intval($_GET['unpublish_report'])));
    } elseif (isset($_GET['delete_post'])) {
        wp_delete_post(intval($_GET['delete_post']), true);
    }
}
add_action('admin_init', 'wp_stat_notice_handle_report_actions');

// Menüpunkt im Admin-Bereich hinzufügen
function wp_stat_notice_add_reported_posts_menu() {
    add_menu_page(
        'Gemeldete Beiträge',
        'Gemeldete Beiträge',
        'manage_options',
        'reported-posts',
        'wp_stat_notice_reported_posts_page',
        'dashicons-warning',
        25
    );
}
add_action('admin_menu', 'wp_stat_notice_add_reported_posts_menu');


/*
 * Verbessertes Gast-Lesezeichen-Plugin mit erhöhter Sicherheit und Benutzerfreundlichkeit
 */


define('STATISTIK_MANAGER_BOOKMARK_POST_TYPE', 'bookmark');
define('STATISTIK_MANAGER_COOKIE_NAME', 'guest_token');
define('STATISTIK_MANAGER_COOKIE_DURATION', 30 * DAY_IN_SECONDS);
define('STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY', 'statistik_manager_bookmarks_');

/**
 * Erstellt den benutzerdefinierten Post-Typ für Lesezeichen.
 */
function statistik_manager_create_bookmark_post_type() {
    register_post_type(STATISTIK_MANAGER_BOOKMARK_POST_TYPE, [
        'labels' => [
            'name' => __('Lesezeichen', 'statistik-manager'),
            'singular_name' => __('Lesezeichen', 'statistik-manager'),
        ],
        'public' => false,
        'show_ui' => false,
        'show_in_menu' => false,
        'supports' => ['title', 'custom-fields'],
    ]);
}
add_action('init', 'statistik_manager_create_bookmark_post_type');

/**
 * Generiert oder holt den Gast-Token.
 *
 * @return string Der Gast-Token.
 */
function statistik_manager_get_guest_token() {
    $guest_token = isset($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME]) ? sanitize_text_field($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME]) : null;

    if (!$guest_token) {
        $guest_token = wp_generate_uuid4();
        setcookie(
            STATISTIK_MANAGER_COOKIE_NAME,
            $guest_token,
            time() + STATISTIK_MANAGER_COOKIE_DURATION,
            COOKIEPATH,
            COOKIE_DOMAIN,
            is_ssl(), // Secure
            true // HttpOnly
        );
    }

    return $guest_token;
}

/**
 * Speichert ein Lesezeichen für einen Gast.
 *
 * @param int $post_id Post-ID des Lesezeichens.
 */
function statistik_manager_save_bookmark($post_id) {
    $guest_token = statistik_manager_get_guest_token();
    update_post_meta($post_id, '_guest_token', $guest_token);
}

/**
 * Ruft die Lesezeichen eines Gastes ab.
 *
 * @return array Liste der Lesezeichen.
 */
function statistik_manager_get_guest_bookmarks() {
    $guest_token = statistik_manager_get_guest_token();
    $cache_key = STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY . md5($guest_token);
    $bookmarks = get_transient($cache_key);

    if ($bookmarks !== false) {
        return $bookmarks;
    }

    $args = [
        'post_type' => STATISTIK_MANAGER_BOOKMARK_POST_TYPE,
        'meta_query' => [
            [
                'key' => '_guest_token',
                'value' => $guest_token,
            ],
        ],
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC',
    ];

    $bookmarks_query = new WP_Query($args);
    $bookmarks = $bookmarks_query->posts;

    set_transient($cache_key, $bookmarks, HOUR_IN_SECONDS);
    return $bookmarks;
}

/**
 * Löscht ein Lesezeichen via AJAX.
 */
function statistik_manager_delete_bookmark() {
    check_ajax_referer('statistik_manager_bookmark_nonce', 'nonce');

    if (!isset($_POST['bookmark_id']) || !isset($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME])) {
        wp_send_json_error(['message' => __('Ungültige Anfrage.', 'statistik-manager')]);
    }

    $bookmark_id = absint($_POST['bookmark_id']);
    $guest_token = sanitize_text_field($_COOKIE[STATISTIK_MANAGER_COOKIE_NAME]);
    $stored_token = get_post_meta($bookmark_id, '_guest_token', true);

    if ($stored_token !== $guest_token) {
        wp_send_json_error(['message' => __('Du kannst nur deine eigenen Lesezeichen löschen.', 'statistik-manager')]);
    }

    wp_delete_post($bookmark_id, true);
    delete_transient(STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY . md5($guest_token));
    wp_send_json_success(['message' => __('Lesezeichen erfolgreich gelöscht.', 'statistik-manager')]);
}
add_action('wp_ajax_delete_bookmark', 'statistik_manager_delete_bookmark');
add_action('wp_ajax_nopriv_delete_bookmark', 'statistik_manager_delete_bookmark');

/**
 * Fügt ein Lesezeichen via AJAX hinzu.
 */
function statistik_manager_add_bookmark_ajax() {
    check_ajax_referer('statistik_manager_bookmark_nonce', 'nonce');

    if (!isset($_POST['bookmark_url']) || !isset($_POST['bookmark_name'])) {
        wp_send_json_error(['message' => __('Bitte alle Felder ausfüllen.', 'statistik-manager')]);
    }

    $bookmark_url = esc_url_raw($_POST['bookmark_url']);
    $bookmark_name = sanitize_text_field($_POST['bookmark_name']);

    if (empty($bookmark_url) || empty($bookmark_name)) {
        wp_send_json_error(['message' => __('Ungültige URL oder Name.', 'statistik-manager')]);
    }

    // Prüfen, ob die URL bereits existiert
    $guest_token = statistik_manager_get_guest_token();
    $args = [
        'post_type' => STATISTIK_MANAGER_BOOKMARK_POST_TYPE,
        'meta_query' => [
            'relation' => 'AND',
            [
                'key' => '_guest_token',
                'value' => $guest_token,
            ],
            [
                'key' => '_bookmark_url',
                'value' => $bookmark_url,
            ],
        ],
        'posts_per_page' => 1,
    ];

    $existing = new WP_Query($args);
    if ($existing->have_posts()) {
        wp_send_json_error(['message' => __('Diese URL ist bereits ein Lesezeichen.', 'statistik-manager')]);
    }

    // Neues Lesezeichen erstellen
    $post_id = wp_insert_post([
        'post_type' => STATISTIK_MANAGER_BOOKMARK_POST_TYPE,
        'post_title' => $bookmark_name,
        'post_status' => 'publish',
        'meta_input' => [
            '_bookmark_url' => $bookmark_url,
            '_guest_token' => $guest_token,
        ],
    ]);

    if (is_wp_error($post_id)) {
        wp_send_json_error(['message' => __('Fehler beim Hinzufügen des Lesezeichens.', 'statistik-manager')]);
    }

    delete_transient(STATISTIK_MANAGER_BOOKMARKS_CACHE_KEY . md5($guest_token));
    wp_send_json_success([
        'message' => __('Lesezeichen erfolgreich hinzugefügt.', 'statistik-manager'),
        'html' => '<li><button class="delete-bookmark-btn" data-bookmark-id="' . esc_attr($post_id) . '">' . esc_html__('Löschen', 'statistik-manager') . '</button><a href="' . esc_url($bookmark_url) . '" target="_blank">' . esc_html($bookmark_name) . '</a></li>',
    ]);
}
add_action('wp_ajax_add_bookmark', 'statistik_manager_add_bookmark_ajax');
add_action('wp_ajax_nopriv_add_bookmark', 'statistik_manager_add_bookmark_ajax');

/**
 * Zeigt die Lesezeichen eines Gastes an.
 *
 * @return string HTML-Ausgabe der Lesezeichen.
 */
function statistik_manager_display_bookmarks() {
    $bookmarks = statistik_manager_get_guest_bookmarks();

    ob_start();
    ?>
    <div class="statistik-manager-bookmarks">
        <h3><?php esc_html_e('Gespeicherte Lesezeichen', 'statistik-manager'); ?></h3>
        <?php if (empty($bookmarks)) : ?>
            <p><?php esc_html_e('Keine Lesezeichen gefunden.', 'statistik-manager'); ?></p>
        <?php else : ?>
            <ul>
                <?php foreach ($bookmarks as $bookmark) : ?>
                    <li>
                        <button class="delete-bookmark-btn" data-bookmark-id="<?php echo esc_attr($bookmark->ID); ?>">
                            <?php esc_html_e('Löschen', 'statistik-manager'); ?>
                        </button>
                        <a href="<?php echo esc_url(get_post_meta($bookmark->ID, '_bookmark_url', true)); ?>" target="_blank">
                            <?php echo esc_html(get_the_title($bookmark)); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Shortcode zum Anzeigen der Lesezeichen.
 *
 * @return string HTML-Ausgabe.
 */
function statistik_manager_bookmarks_shortcode() {
    return statistik_manager_display_bookmarks();
}
add_shortcode('display_bookmarks', 'statistik_manager_bookmarks_shortcode');

/**
 * Shortcode zum Hinzufügen eines Lesezeichens.
 *
 * @return string HTML-Ausgabe.
 */
function statistik_manager_add_bookmark_shortcode() {
    ob_start();
    ?>
    <form id="add-bookmark-form" class="statistik-manager-bookmark-form">
        <input type="hidden" name="nonce" value="<?php echo esc_attr(wp_create_nonce('statistik_manager_bookmark_nonce')); ?>">
        <div class="form-field">
            <label for="bookmark_name"><?php esc_html_e('Name des Lesezeichens:', 'statistik-manager'); ?></label>
            <input type="text" name="bookmark_name" id="bookmark_name" required>
        </div>
        <div class="form-field">
            <label for="bookmark_url"><?php esc_html_e('URL des Lesezeichens:', 'statistik-manager'); ?></label>
            <input type="url" name="bookmark_url" id="bookmark_url" required>
        </div>
        <div class="form-field">
            <button type="submit"><?php esc_html_e('Lesezeichen hinzufügen', 'statistik-manager'); ?></button>
        </div>
        <div class="form-message"></div>
    </form>
    <style>
        .statistik-manager-bookmark-form { max-width: 500px; margin: 20px 0; }
        .statistik-manager-bookmark-form .form-field { margin-bottom: 15px; }
        .statistik-manager-bookmark-form label { display: block; margin-bottom: 5px; font-weight: bold; }
        .statistik-manager-bookmark-form input { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        .statistik-manager-bookmark-form button { background-color: #0073aa; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
        .statistik-manager-bookmark-form button:hover { background-color: #005177; }
        .statistik-manager-bookmark-form .form-message { margin-top: 10px; color: green; }
        .statistik-manager-bookmark-form .form-message.error { color: red; }
        .statistik-manager-bookmarks ul { list-style: none; padding: 0; }
        .statistik-manager-bookmarks li { margin-bottom: 10px; display: flex; align-items: center; }
        .statistik-manager-bookmarks button { margin-right: 10px; background-color: #d63638; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer; }
        .statistik-manager-bookmarks button:hover { background-color: #a12b2d; }
        @media (max-width: 600px) {
            .statistik-manager-bookmark-form input, .statistik-manager-bookmark-form button { font-size: 14px; }
            .statistik-manager-bookmarks li { flex-direction: column; align-items: flex-start; }
            .statistik-manager-bookmarks button { margin-bottom: 5px; }
        }
    </style>
    <?php
    return ob_get_clean();
}
add_shortcode('add_bookmark', 'statistik_manager_add_bookmark_shortcode');

/**
 * Fügt JavaScript für AJAX-Interaktionen hinzu.
 */
function statistik_manager_add_bookmark_script() {
    if (!is_singular() && !has_shortcode(get_the_content(), 'add_bookmark') && !has_shortcode(get_the_content(), 'display_bookmarks')) {
        return;
    }
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#add-bookmark-form').on('submit', function(e) {
                e.preventDefault();

                var $form = $(this);
                var $message = $form.find('.form-message');
                var data = {
                    action: 'add_bookmark',
                    nonce: $form.find('[name="nonce"]').val(),
                    bookmark_url: $form.find('#bookmark_url').val(),
                    bookmark_name: $form.find('#bookmark_name').val(),
                };

                $.post('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', data, function(response) {
                    $message.removeClass('error');
                    if (response.success) {
                        $message.addClass('success').text(response.data.message);
                        $('.statistik-manager-bookmarks ul').append(response.data.html);
                        $form.find('#bookmark_url, #bookmark_name').val('');
                    } else {
                        $message.addClass('error').text(response.data.message);
                    }
                });
            });

            $('body').on('click', '.delete-bookmark-btn', function() {
                var $button = $(this);
                var bookmarkId = $button.data('bookmark-id');
                var data = {
                    action: 'delete_bookmark',
                    nonce: $('#add-bookmark-form [name="nonce"]').val(),
                    bookmark_id: bookmarkId,
                };

                $.post('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', data, function(response) {
                    var $message = $('.statistik-manager-bookmark-form .form-message');
                    $message.removeClass('error success');
                    if (response.success) {
                        $message.addClass('success').text(response.data.message);
                        $button.closest('li').remove();
                    } else {
                        $message.addClass('error').text(response.data.message);
                    }
                });
            });
        });
    </script>
    <?php
}
add_action('wp_footer', 'statistik_manager_add_bookmark_script');


/*
* Statistik & Banner
*/


// Funktion zum Einbinden von CSS direkt im Plugin-Code
function statistik_manager_inline_styles() {
    ?>
    <style>
        /* CSS für das Statistik Manager Plugin */
        .statistik-manager-bookmarks {
            font-family: Arial, sans-serif;
            margin-top: 20px;
        }
        .statistik-manager-bookmarks ul {
            list-style-type: none;
            padding: 0;
        }
        .statistik-manager-bookmarks li {
            margin-bottom: 10px;
        }
        .statistik-manager-bookmarks a {
            text-decoration: none;
            color: #0073aa;
            font-size: 1.6em; /* Größerer Text für den Titel */
        }
        .statistik-manager-bookmarks a:hover {
            color: #005177;
        }
        .delete-bookmark-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            margin-right: 10px; /* Abstand zwischen Button und Titel */
            margin-bottom: 10px; /* Mehr Abstand nach unten */
        }
        .delete-bookmark-btn:hover {
            background-color: #d32f2f;
        }
        .form-field {
            margin-bottom: 15px;
        }
        .form-field label {
            display: block;
            margin-bottom: 5px;
        }
        .form-field input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .form-field button {
            background-color: #0073aa;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
        }
        .form-field button:hover {
            background-color: #005177;
        }
    </style>
    <?php
}
add_action('wp_head', 'statistik_manager_inline_styles');

// Font Awesome einbinden
function statistik_manager_enqueue_fontawesome() {
    wp_enqueue_style('fontawesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css', [], null);
}
add_action('wp_enqueue_scripts', 'statistik_manager_enqueue_fontawesome');

// Sprachdateien laden
function statistik_manager_load_textdomain() {
    load_plugin_textdomain('statistik-manager', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
add_action('plugins_loaded', 'statistik_manager_load_textdomain');

// Funktion zum Abrufen der Statistiken
function statistik_manager_get_statistics() {
    global $wpdb;

    // Beiträge
    $posts_count = wp_count_posts()->publish;

    // Kommentare
    $comments_count = wp_count_comments()->total_comments;

    // Kategorien
    $selected_categories = get_option('statistik_manager_selected_categories', []);
    $categories_count = 0;

    if (!empty($selected_categories)) {
        $categories_count = count($selected_categories);
    } else {
        // Alle Kategorien zählen, wenn keine ausgewählt wurden
        $categories_count = wp_count_terms('category');
    }

    // Serien (angenommen, Serien sind benutzerdefinierte Taxonomie)
    $series_count = wp_count_terms('series'); // 'series' ist die benutzerdefinierte Taxonomie

    // Eröffnungsdatum
    $opening_date = get_option('statistik_manager_opening_date', '');

    return [
        'posts_count' => $posts_count,
        'comments_count' => $comments_count,
        'categories_count' => $categories_count,
        'series_count' => $series_count,
        'opening_date' => $opening_date
    ];
}

		// Banner-Funktion
		function statistik_manager_display_banner($position) {
			if (!get_option('statistik_manager_banner_enabled', 1)) {
				return;
			}

			$banner_text = get_option('statistik_manager_banner_text', 'Willkommen auf unserer Webseite!');
			$banner_color = get_option('statistik_manager_banner_color', '#0073aa');
			$banner_position = get_option('statistik_manager_banner_position', 'top');
			$font_size = get_option('statistik_manager_banner_font_size', 'medium');
			$banner_icon = get_option('statistik_manager_banner_icon', 'fas fa-info-circle'); // Standard-Icon
			$show_icon = get_option('statistik_manager_show_icon', 1); // Option zur Aktivierung des Icons

			// Schriftgröße je nach Auswahl setzen
			switch ($font_size) {
				case 'small':
					$font_size_css = '14px';
					break;
				case 'medium':
					$font_size_css = '18px';
					break;
				case 'large':
					$font_size_css = '24px';
					break;
				default:
					$font_size_css = '18px';
			}

			if ($banner_position !== $position) {
				return;
			}

			// Standard-Styles für das Banner
			$style = "background-color: " . esc_attr($banner_color) . ";
					  color: #fff;
					  text-align: center;
					  padding: 10px;
					  width: 100%;
					  height: 50px; /* Feste Höhe */
					  line-height: 30px; /* Zentrierte Schrift */
					  z-index: 9999;
					  position: fixed;
					  top: 0;
					  left: 0;";

			$text_style = "font-size: " . esc_attr($font_size_css) . ";"; 
			$icon_style = "font-size: 24px; margin-right: 8px;"; // Feste Größe für Icon

			echo '<div class="statistik-manager-banner" id="statistik-manager-banner" style="' . esc_attr($style) . '">';
			
			// Icon nur anzeigen, wenn gewünscht
			if ($show_icon && !empty($banner_icon)) {
				echo '<i class="' . esc_attr($banner_icon) . '" style="' . esc_attr($icon_style) . '"></i>';
			}

			echo '<span style="' . esc_attr($text_style) . '">' . esc_html($banner_text) . '</span>';
			echo '</div>';
		}

		// Funktion für das Banner im Header (nach <body>)
		function statistik_manager_display_banner_header() {
			add_action('wp_body_open', function() {
				statistik_manager_display_banner('top');
			});
		}

		// Falls `wp_body_open` nicht unterstützt wird, als Fallback `wp_footer` nutzen
		function statistik_manager_display_banner_header_fallback() {
			add_action('wp_footer', function() {
				statistik_manager_display_banner('top');
			}, 5);
		}

		// Funktion für das Banner im Footer
		function statistik_manager_display_banner_footer() {
			add_action('wp_footer', function() {
				statistik_manager_display_banner('bottom');
			}, 10);
		}

		// Banner laden (Header mit Fallback)
		if (function_exists('wp_body_open')) {
			statistik_manager_display_banner_header();
		} else {
			statistik_manager_display_banner_header_fallback();
		}

		// Fix: Admin-Leiste (Wenn Admin angemeldet ist, Banner nach unten verschieben)
		function statistik_manager_admin_bar_fix() {
			if (is_admin_bar_showing()) {
				echo '<style>
					#statistik-manager-banner {
						top: 32px !important; /* Admin-Leiste ausgleichen */
					}
					body {
						padding-top: 82px !important; /* Extra Platz für Admin-Leiste */
					}
				</style>';
			} else {
				echo '<style>
					body {
						padding-top: 70px !important; /* Standard Abstand */
					}
				</style>';
			}
		}
		add_action('wp_head', 'statistik_manager_admin_bar_fix');

// Shortcode für die Anzeige der Statistiken
function statistik_manager_shortcode() {
    $statistics = statistik_manager_get_statistics();
    $webseitenname = get_bloginfo('name');

    $output = '<div class="statistik-manager">';
    $output .= '<h3>Statistikübersicht</h3>';
    $output .= '<div class="statistik-items">';

    if (get_option('statistik_manager_show_posts')) {
        $output .= '<div class="stat-item"><i class="fas fa-file-alt"></i>';
        $output .= '<p><strong>Beiträge:</strong></br> ' . $statistics['posts_count'] . '</p></div>';
    }
    if (get_option('statistik_manager_show_comments')) {
        $output .= '<div class="stat-item"><i class="fas fa-comments"></i>';
        $output .= '<p><strong>Kommentare:</strong></br> ' . $statistics['comments_count'] . '</p></div>';
    }
    if (get_option('statistik_manager_show_categories')) {
        $output .= '<div class="stat-item"><i class="fas fa-th-list"></i>';
        $output .= '<p><strong>Kategorien:</strong></br> ' . $statistics['categories_count'] . '</p></div>';
    }
    if (get_option('statistik_manager_show_series')) {
        $output .= '<div class="stat-item"><i class="fas fa-tv"></i>';
        $output .= '<p><strong>Serien:</strong></br> ' . $statistics['series_count'] . '</p></div>';
    }
    $output .= '</div>';

    // Eröffnungsdatum anzeigen, wenn gesetzt
    if (!empty($statistics['opening_date'])) {
        $formatted_date = date('d.m.Y', strtotime($statistics['opening_date']));
        $output .= '<div class="stat-opening-date">';
        $output .= '<i class="fas fa-calendar-alt"></i>'; 
        $output .= '<p><strong>' . sprintf(__('%s wurde am %s eröffnet.', 'statistik-manager'), esc_html($webseitenname), esc_html($formatted_date)) . '</strong></p>';
        $output .= '</div>';
    }

    $output .= '</div>';
    return $output;
}

add_shortcode('statistik_manager', 'statistik_manager_shortcode');

// Admin-Panel CSS einbinden, nur auf der Plugin-Seite
function statistik_manager_enqueue_admin_styles($hook) {
    if ($hook === 'toplevel_page_statistik_manager') {
        wp_enqueue_style('statistik-manager-admin-style', plugins_url('css/admin-style.css', __FILE__));
    }
}
add_action('admin_enqueue_scripts', 'statistik_manager_enqueue_admin_styles');

// Frontend CSS nur einbinden, wenn der Shortcode verwendet wird
function statistik_manager_enqueue_frontend_styles() {
    if (has_shortcode(get_post()->post_content, 'statistik_manager')) {
        wp_enqueue_style('statistik-manager-frontend-style', plugins_url('css/style.css', __FILE__));
    }
}
add_action('wp_enqueue_scripts', 'statistik_manager_enqueue_frontend_styles');

function statistik_manager_menu() {
    add_menu_page(
        'WP Stat & Notice', // Ändern Sie den Seitentitel
        'WP Stat & Notice', // Ändern Sie die Menübezeichnung
        'manage_options',    // Berechtigungen
        'statistik_manager', // Menü-Slug
        'statistik_manager_options_page', // Callback-Funktion
        'dashicons-chart-pie' // Dashicon-Icon
    );
}
add_action('admin_menu', 'statistik_manager_menu');

// Funktion für die Plugin-Optionen-Seite
function statistik_manager_options_page() {
    ?>
    <div class="wrap">
        <h1><?php _e('WP Stat & Notice Einstellungen', 'statistik-manager'); ?></h1>

        <div class="statistik-manager-logo">
            <img src="https://m-viper.de/img/logo.png" alt="Dein Logo" style="max-width: 200px;"/>
        </div>

        <div class="statistik-manager-content">
            <div class="statistik-manager-settings">
                <form method="post" action="options.php">
                    <?php
                    settings_fields('statistik_manager_settings_group');
                    do_settings_sections('statistik_manager');
                    ?>
                    <h2><?php _e('Statistiken anzeigen', 'statistik-manager'); ?></h2>
                    <table class="form-table">
                        <tr valign="top">
                            <th scope="row"><?php _e('Anzeigen', 'statistik-manager'); ?></th>
                            <td>
                                <input type="checkbox" name="statistik_manager_show_posts" value="1" <?php checked(get_option('statistik_manager_show_posts'), 1); ?> />
                                <label for="statistik_manager_show_posts"><?php _e('Beiträge anzeigen', 'statistik-manager'); ?></label><br>
                                <input type="checkbox" name="statistik_manager_show_comments" value="1" <?php checked(get_option('statistik_manager_show_comments'), 1); ?> />
                                <label for="statistik_manager_show_comments"><?php _e('Kommentare anzeigen', 'statistik-manager'); ?></label><br>
                                <input type="checkbox" name="statistik_manager_show_categories" value="1" <?php checked(get_option('statistik_manager_show_categories'), 1); ?> />
                                <label for="statistik_manager_show_categories"><?php _e('Kategorien anzeigen', 'statistik-manager'); ?></label><br>
                                <input type="checkbox" name="statistik_manager_show_series" value="1" <?php checked(get_option('statistik_manager_show_series'), 1); ?> />
                                <label for="statistik_manager_show_series"><?php _e('Serien anzeigen', 'statistik-manager'); ?></label>
                            </td>
                        </tr>
                    </table>

                    <h2><?php _e('Kategorien auswählen', 'statistik-manager'); ?></h2>
                    <table class="form-table">
                        <tr valign="top">
                            <th scope="row"><?php _e('Angezeigte Kategorien', 'statistik-manager'); ?></th>
                            <td>
                                <?php
                                $categories = get_terms(array(
                                    'taxonomy' => 'category',
                                    'orderby' => 'name',
                                    'order' => 'ASC',
                                    'hide_empty' => false,
                                ));

                                if (!empty($categories) && !is_wp_error($categories)) :
                                    $selected_categories = get_option('statistik_manager_selected_categories', []);
                                    ?>
                                    <select name="statistik_manager_selected_categories[]" multiple="multiple" style="width: 300px; height: 150px;">
                                        <?php foreach ($categories as $category) : ?>
                                            <option value="<?php echo esc_attr($category->term_id); ?>"
                                                <?php echo in_array($category->term_id, $selected_categories) ? 'selected' : ''; ?>>
                                                <?php echo esc_html($category->name); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>

                    <h2><?php _e('Eröffnungsdatum der Webseite', 'statistik-manager'); ?></h2>
                    <table class="form-table">
                        <tr valign="top">
                            <th scope="row"><?php _e('Eröffnungsdatum', 'statistik-manager'); ?></th>
                            <td>
                                <input type="date" name="statistik_manager_opening_date" value="<?php echo esc_attr(get_option('statistik_manager_opening_date')); ?>" />
                            </td>
                        </tr>
                    </table>

                    <h2>Banner-Einstellungen</h2>
				<table class="form-table">
					<tr>
						<th>Banner anzeigen</th>
						<td>
							<input type="checkbox" name="statistik_manager_banner_enabled" value="1" <?php checked(get_option('statistik_manager_banner_enabled', 1)); ?> />
							<label for="statistik_manager_banner_enabled">Banner aktivieren</label>
						</td>
					</tr>
					<tr>
						<th>Banner Text</th>
						<td><input type="text" name="statistik_manager_banner_text" value="<?php echo esc_attr(get_option('statistik_manager_banner_text', 'Willkommen auf unserer Webseite!')); ?>" /></td>
					</tr>
					<tr>
						<th>Banner Farbe</th>
						<td><input type="color" name="statistik_manager_banner_color" value="<?php echo esc_attr(get_option('statistik_manager_banner_color', '#0073aa')); ?>" /></td>
					</tr>
					<tr>
						<th>Banner Position</th>
						<td>
							<select name="statistik_manager_banner_position">
								<option value="top" <?php selected(get_option('statistik_manager_banner_position'), 'top'); ?>>Oben</option>
								<option value="bottom" <?php selected(get_option('statistik_manager_banner_position'), 'bottom'); ?>>Unten</option>
							</select>
						</td>
					</tr>
					<tr>
					<tr>
					<th>Icon auswählen</th>
					<td>
						<select name="statistik_manager_banner_icon">
							<option value="fas fa-info-circle" <?php selected(get_option('statistik_manager_banner_icon'), 'fas fa-info-circle'); ?>>ℹ️ Info</option>
							<option value="fas fa-exclamation-triangle" <?php selected(get_option('statistik_manager_banner_icon'), 'fas fa-exclamation-triangle'); ?>>⚠️ Warnung</option>
							<option value="fas fa-bell" <?php selected(get_option('statistik_manager_banner_icon'), 'fas fa-bell'); ?>>🔔 Benachrichtigung</option>
							<option value="fas fa-thumbs-up" <?php selected(get_option('statistik_manager_banner_icon'), 'fas fa-thumbs-up'); ?>>👍 Daumen hoch</option>
							<option value="">Kein Icon</option>
						</select>
					</td>
				</tr>
				<tr>
					<th>Icon anzeigen</th>
					<td>
						<input type="checkbox" name="statistik_manager_show_icon" value="1" <?php checked(get_option('statistik_manager_show_icon', 1)); ?> />
						<label for="statistik_manager_show_icon">Icon anzeigen</label>
					</td>
				</tr>
				<tr>
					<th>Schriftgröße</th>
					<td>
						<select name="statistik_manager_banner_font_size">
							<option value="small" <?php selected(get_option('statistik_manager_banner_font_size'), 'small'); ?>>Klein</option>
							<option value="medium" <?php selected(get_option('statistik_manager_banner_font_size'), 'medium'); ?>>Mittel</option>
							<option value="large" <?php selected(get_option('statistik_manager_banner_font_size'), 'large'); ?>>Groß</option>
						</select>
					</td>
				</tr>
				</table>

                    <?php submit_button(); ?>
                </form>
            </div>

            <!-- Box mit weiteren Plugins -->
<div class="statistik-manager-advertisement">
<div class="statistik-manager-plugins">
    <h3><?php _e('Weitere Plugins', 'statistik-manager'); ?></h3>
    <ul>
        <li><a href="https://git.viper.ipv64.net/M_Viper/wp-multi-toolkit">WP-Multi Toolkit</a></li>
        <li><a href="https://git.viper.ipv64.net/M_Viper/wp-multi">WP-Multi</a></li>
        <li><a href="https://git.viper.ipv64.net/M_Viper/WP-Multi-Search">WP-Multi Search</a></li>
        <li><a href="https://git.viper.ipv64.net/M_Viper/wp-multi-comment-notifications">WP-Multi Comment Notification</a></li>
        <li><a href="https://git.viper.ipv64.net/M_Viper/WP-Multi-Kategorie">WP-Multi Kategorie</a></li>
    </ul>
</div>

<!-- Nützliche Informationen Box -->
<div class="statistik-manager-advertisement">
    <h3>Kurzanleitung für den Statistik Manager</h3>
    <p>Verwenden Sie den Statistik Manager, um eine benutzerdefinierte Statistik Box auf Ihrer Website anzuzeigen und wichtige Statistiken zu verfolgen. Hier ist eine kurze Anleitung:</p>
    <ol>
        <li><strong>Fügen Sie den Shortcode ein:</strong> Um die Statistik Box anzuzeigen, fügen Sie den folgenden Shortcode an der gewünschten Stelle in Ihrem Beitrag oder Ihrer Seite ein: <code>[statistik_manager]</code>.</li>
        <li><strong>Statistiken anzeigen:</strong> Die Statistik Box zeigt automatisch verschiedene Statistiken an. Sie können folgende Statistiken anzeigen lassen:
            <ul>
                <li><strong>Beiträge:</strong> Zeigt die Gesamtzahl der veröffentlichten Beiträge auf Ihrer Webseite.</li>
                <li><strong>Kommentare:</strong> Zeigt die Gesamtzahl der eingegangenen Kommentare auf Ihren Beiträgen.</li>
                <li><strong>Kategorien:</strong> Zeigt die Anzahl der erstellten Kategorien auf Ihrer Webseite.</li>
                <li><strong>Serien:</strong> Zeigt die Gesamtzahl der Serien, falls Ihre Seite Serieninhalte enthält.</li>
            </ul>
        </li>
        <li><strong>Auswahl der zu zählenden Kategorien:</strong> In den Plugin-Einstellungen können Sie auswählen, welche Kategorien in die Statistik einbezogen werden sollen, z. B. Kommentare, Beiträge oder benutzerdefinierte Kategorien.</li>
        <li><strong>Eröffnungsdatum der Webseite:</strong> Das Eröffnungsdatum Ihrer Website wird automatisch in der Statistik Box angezeigt, damit Besucher sehen können, wie lange Ihre Seite bereits online ist.</li>
        <li><strong>Banner hinzufügen:</strong> Sie können in den Plugin-Einstellungen auch ein Banner für die Statistik Box hinzufügen, das individuell angepasst werden kann (z. B. als Werbung oder für besondere Hinweise).</li>
    </ol>
    <p>Die Statistik Box wird an der Stelle angezeigt, an der der Shortcode eingefügt wurde. Alle Statistiken und Inhalte können jederzeit über die Plugin-Einstellungen angepasst werden.</p>
    <p>Bei Fragen oder Problemen können Sie sich jederzeit an uns wenden!</p>

    <h3>Kurzanleitung zur Lesezeichen-Verwaltung</h3>
    <p>Zusätzlich zur Anzeige von Statistiken können Sie auch eine benutzerdefinierte Liste von Lesezeichen für Ihre Gäste verwalten. Hier sind die wichtigen Schritte:</p>
    <ol>
        <li><strong>Fügen Sie den Shortcode für Lesezeichen ein:</strong> Um die Lesezeichen-Liste anzuzeigen, fügen Sie den folgenden Shortcode an der gewünschten Stelle in Ihrem Beitrag oder Ihrer Seite ein: <code>[display_bookmarks]</code>.</li>
        <li><strong>Lesezeichen hinzufügen:</strong> Besucher können Lesezeichen zu Ihren Seiten hinzufügen. Diese erscheinen automatisch in der Liste der gespeicherten Lesezeichen. Um ein Lesezeichen hinzuzufügen, müssen sie den Shortcode <code>[add_bookmark]</code> verwenden, der ein Formular zum Speichern eines Lesezeichens anzeigt.</li>
        <li><strong>Lesezeichen löschen:</strong> Sie können Lesezeichen jederzeit löschen, indem Sie auf den „Lesezeichen Löschen“-Button neben dem jeweiligen Eintrag klicken. Nur der Besitzer des Lesezeichens kann es löschen.</li>
    </ol>
    <p>Wenn Sie Fragen oder Probleme haben, wenden Sie sich an uns!</p>
</div>

</div>
    </div>
    <?php
}

// Optionen registrieren
function statistik_manager_register_settings() {
    register_setting('statistik_manager_settings_group', 'statistik_manager_show_posts');
    register_setting('statistik_manager_settings_group', 'statistik_manager_show_comments');
    register_setting('statistik_manager_settings_group', 'statistik_manager_show_categories');
    register_setting('statistik_manager_settings_group', 'statistik_manager_show_series');
    register_setting('statistik_manager_settings_group', 'statistik_manager_selected_categories');
    register_setting('statistik_manager_settings_group', 'statistik_manager_opening_date');
    register_setting('statistik_manager_settings_group', 'statistik_manager_banner_text');
	register_setting('statistik_manager_settings_group', 'statistik_manager_banner_color');
	register_setting('statistik_manager_settings_group', 'statistik_manager_banner_position');
	register_setting('statistik_manager_settings_group', 'statistik_manager_banner_enabled');
	register_setting('statistik_manager_settings_group', 'statistik_manager_banner_icon');
    register_setting('statistik_manager_settings_group', 'statistik_manager_show_icon');
    register_setting('statistik_manager_settings_group', 'statistik_manager_banner_font_size');

}
add_action('admin_init', 'statistik_manager_register_settings');

// Standardwerte setzen
function statistik_manager_set_default_options() {
    if (get_option('statistik_manager_show_posts') === false) {
        update_option('statistik_manager_show_posts', 1);
    }
    if (get_option('statistik_manager_show_comments') === false) {
        update_option('statistik_manager_show_comments', 1);
    }
    if (get_option('statistik_manager_show_categories') === false) {
        update_option('statistik_manager_show_categories', 1);
    }
    if (get_option('statistik_manager_show_series') === false) {
        update_option('statistik_manager_show_series', 1);
    }
    if (get_option('statistik_manager_selected_categories') === false) {
        update_option('statistik_manager_selected_categories', []);
    }
	if (get_option('statistik_manager_banner_enabled') === false) {
        update_option('statistik_manager_banner_enabled', 1);
    }
	if (get_option('statistik_manager_banner_font_size') === false) {
    update_option('statistik_manager_banner_font_size', 'medium');
}

}
add_action('admin_init', 'statistik_manager_set_default_options');