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

/*
* 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;";

    // Tabelle zuerst erstellen bzw. aktualisieren - erst danach kann die
    // Spaltenprüfung laufen (vorher schlug SHOW COLUMNS bei der Erstaktivierung fehl).
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);

    // Migration für Alt-Installationen: Spalte `name` ergänzen, falls sie fehlt
    $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");

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

    if (!in_array('name', $column_names, true)) {
        $wpdb->query("ALTER TABLE $table_name ADD COLUMN `name` VARCHAR(255) NOT NULL");
    }
}

register_activation_hook(WP_MULTI_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");

    wpmt_admin_page_open(
        __('Gemeldete Beiträge', 'wp-stat-notice'),
        __('Von Besuchern gemeldete Inhalte prüfen und bearbeiten', 'wp-stat-notice')
    );

    wpmt_admin_card_open();
    if (empty($reports)) {
        wpmt_admin_notice('info', __('Es liegen keine Meldungen vor.', 'wp-stat-notice'));
    } else {
        ?>
        <div class="wpm-table-wrap">
        <table class="wpm-table">
            <thead>
                <tr>
                    <th><?php _e('Beitrag', 'wp-stat-notice'); ?></th>
                    <th><?php _e('Datum', 'wp-stat-notice'); ?></th>
                    <th><?php _e('Name', 'wp-stat-notice'); ?></th>
                    <th><?php _e('Grund', 'wp-stat-notice'); ?></th>
                    <th><?php _e('Status', 'wp-stat-notice'); ?></th>
                    <th><?php _e('Aktionen', 'wp-stat-notice'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($reports as $report):
                    $post = get_post($report->post_id); ?>
                    <tr>
                        <td><?php echo $post ? 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><span class="wpm-badge <?php echo $report->status === 'reported' ? 'wpm-badge--warning' : ''; ?>"><?php echo esc_html($report->status); ?></span></td>
                        <td>
                            <a href="<?php echo esc_url(wp_nonce_url('?page=reported-posts&delete_report=' . $report->id, 'wp_stat_notice_delete_report_' . $report->id)); ?>" class="wpm-btn" onclick="return confirm('<?php esc_attr_e('Report wirklich löschen?', 'wp-stat-notice'); ?>');"><?php _e('Report löschen', 'wp-stat-notice'); ?></a>
                            <a href="<?php echo esc_url(wp_nonce_url('?page=reported-posts&unpublish_report=' . $report->id, 'wp_stat_notice_unpublish_report_' . $report->id)); ?>" class="wpm-btn"><?php _e('Unpublish', 'wp-stat-notice'); ?></a>
                            <a href="<?php echo esc_url(wp_nonce_url('?page=reported-posts&delete_post=' . $report->post_id, 'wp_stat_notice_delete_post_' . $report->post_id)); ?>" class="wpm-btn wpm-btn--danger" onclick="return confirm('<?php esc_attr_e('Beitrag wirklich unwiderruflich löschen?', 'wp-stat-notice'); ?>');"><?php _e('Beitrag löschen', 'wp-stat-notice'); ?></a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php
    }
    wpmt_admin_card_close();

    wpmt_admin_page_close();
}

// Aktionen für Report-Handling
function wp_stat_notice_handle_report_actions() {
    if (!isset($_GET['page']) || $_GET['page'] !== 'reported-posts') {
        return;
    }

    if (!current_user_can('manage_options')) {
        return;
    }

    global $wpdb;
    if (isset($_GET['delete_report'])) {
        check_admin_referer('wp_stat_notice_delete_report_' . intval($_GET['delete_report']));
        $wpdb->delete($wpdb->prefix . 'reported_posts', array('id' => intval($_GET['delete_report'])), array('%d'));
    } elseif (isset($_GET['unpublish_report'])) {
        check_admin_referer('wp_stat_notice_unpublish_report_' . intval($_GET['unpublish_report']));
        $wpdb->update($wpdb->prefix . 'reported_posts', array('status' => 'unpublished'), array('id' => intval($_GET['unpublish_report'])), array('%s'), array('%d'));
    } elseif (isset($_GET['delete_post'])) {
        check_admin_referer('wp_stat_notice_delete_post_' . intval($_GET['delete_post']));
        wp_delete_post(intval($_GET['delete_post']), true);
    }
}
add_action('admin_init', 'wp_stat_notice_handle_report_actions');

// Der Menüpunkt "Gemeldete Beiträge" wird zentral in wp_multi_register_admin_menus() registriert.


