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

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

    global $wpdb;
    $table_name = $wpdb->prefix . 'message_board';
    $created = false;

    // Nachricht erstellen (VOR der Ausgabe, damit sie sofort erscheint)
    if (isset($_POST['submit_message']) && !empty($_POST['new_message'])) {
        if (!isset($_POST['wp_multi_pinwand_nonce_field']) || !wp_verify_nonce(wp_unslash($_POST['wp_multi_pinwand_nonce_field']), 'wp_multi_pinwand_create_message')) {
            wp_die(__('Ungültige oder abgelaufene Anfrage.', 'wp-multi'));
        }
        $wpdb->insert(
            $table_name,
            array(
                'message' => sanitize_textarea_field(wp_unslash($_POST['new_message'])),
                'user_id' => get_current_user_id(),
            )
        );
        $created = true;
    }

    $messages = $wpdb->get_results("SELECT * FROM $table_name ORDER BY created_at DESC");

    wpmt_admin_page_open(
        __('Pinwand', 'wp-multi'),
        __('Interne Nachrichten für das Admin-Team', 'wp-multi')
    );

    if ($created) {
        wpmt_admin_notice('success', __('Nachricht wurde erfolgreich erstellt.', 'wp-multi'));
    }

    wpmt_admin_card_open(__('Neue Nachricht erstellen', 'wp-multi'));
    ?>
        <form method="post">
            <?php wp_nonce_field('wp_multi_pinwand_create_message', 'wp_multi_pinwand_nonce_field'); ?>
            <textarea name="new_message" rows="4" required style="width:100%;"></textarea>
            <p><input type="submit" name="submit_message" value="<?php esc_attr_e('Nachricht erstellen', 'wp-multi'); ?>" class="wpm-btn wpm-btn--primary"></p>
        </form>
    <?php
    wpmt_admin_card_close();

    wpmt_admin_card_open(__('Nachrichten', 'wp-multi'));
    if ($messages) {
        echo '<div class="wpm-modules">';
        foreach ($messages as $message) {
            $user_info = get_userdata($message->user_id);
            $author = $user_info ? $user_info->user_login : __('Unbekannt', 'wp-multi');
            printf(
                '<div class="wpm-module" style="cursor:pointer;" onclick="openMessagePopup(%d)"><span class="dashicons dashicons-admin-comments"></span><span><span class="wpm-module__title">%s</span><p class="wpm-module__desc">%s</p><p class="wpm-module__desc">%s</p></span></div>',
                (int) $message->id,
                esc_html($author),
                esc_html(date('d-m-Y H:i', strtotime($message->created_at))),
                esc_html(wp_trim_words($message->message, 20))
            );
        }
        echo '</div>';
    } else {
        wpmt_admin_notice('info', __('Keine Nachrichten vorhanden.', 'wp-multi'));
    }
    wpmt_admin_card_close();

    wpmt_admin_page_close();
    ?>

    <div id="messagePopup" style="display:none; position:fixed; top:20%; left:50%; transform:translateX(-50%); background:#fff; padding:24px; border-radius:12px; box-shadow:0 4px 30px rgba(0,0,0,.2); z-index:99999; max-width:600px; width:90%;">
        <div id="messageContent"></div>
        <div style="display:flex; gap:10px; margin-top:20px;">
            <button onclick="closeMessagePopup()" class="wpm-btn wpm-btn--primary"><?php esc_html_e('Schließen', 'wp-multi'); ?></button>
            <button id="deleteMessageBtn" class="wpm-btn wpm-btn--danger" onclick="deleteMessage()"><?php esc_html_e('Löschen', 'wp-multi'); ?></button>
        </div>
    </div>

    <script>
        var wpMultiPinwandNonce = '<?php echo esc_js(wp_create_nonce('wp_multi_pinwand_nonce')); ?>';

        function openMessagePopup(messageId) {
            var data = { 'action': 'wp_multi_get_message', 'message_id': messageId, 'nonce': wpMultiPinwandNonce };
            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('messagePopup').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, 'nonce': wpMultiPinwandNonce };
            jQuery.post(ajaxurl, data, function(response) {
                if (response == 'success') { closeMessagePopup(); location.reload(); }
            });
        }
    </script>
    <?php
}

// Der Pinwand-Menüpunkt wird zentral in wp_multi_register_admin_menus() registriert.

// Funktion zum Abrufen der vollständigen Nachricht
function wp_multi_get_message() {
    check_ajax_referer('wp_multi_pinwand_nonce', 'nonce');

    if (!current_user_can('administrator')) {
        wp_die();
    }

    if (isset($_POST['message_id'])) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'message_board';
        $message_id = intval($_POST['message_id']);
        $message = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $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() {
    check_ajax_referer('wp_multi_pinwand_nonce', 'nonce');

    if (!current_user_can('administrator')) {
        wp_die();
    }

    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), array('%d'));

        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(WP_MULTI_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>';
    }
}


