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

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

/*
 * Discord Notify
 */

// Einstellungsseite für Discord Webhook
function wp_multi_settings_page() {
    wpmt_admin_page_open(
        __('DC-Notify', 'wp-multi'),
        __('Discord-Benachrichtigungen bei neuen Beiträgen', 'wp-multi')
    );

    wpmt_admin_card_open();
    ?>
        <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>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}

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

