<?php
/**
 * WP Multi – Modul: Telegram-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; }

/*
* Telegram Notify
*/


// Admin-Seiten Callback
function tg_notify_page() {
    wpmt_admin_page_open(
        __('TG-Notify', 'wp-stat-notice'),
        __('Telegram-Benachrichtigungen bei neuen Beiträgen', 'wp-stat-notice')
    );

    wpmt_admin_card_open();
    ?>
    <form method="post" action="options.php">
        <?php
        settings_fields('tg_notify_options_group');
        do_settings_sections('tg-notify');
        submit_button('Speichern', 'primary', 'submit', true);
        ?>
    </form>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}

// 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();
                }
            } 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();
                }
            }
        }
    }
}

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


