<?php
/**
 * Plugin Name: MBSM Comment Spam Moderation
 * Plugin URI: https://mbsm.tn/
 * Description: Advanced comment moderation tool by MBSM Group. Features Smart Clean, Name Replacement, Live Table Refresh, and an Editor for Smart Replies.
 * Version: 1.6.0
 * Author: MBSM Group
 * Author URI: https://www.mbsm.tn/
 * Text Domain: mbsm-comment-spam-moderation
 * Domain Path: /languages
 * Requires at least: 5.0
 * Requires PHP: 7.4
 * @copyright 2025 MBSM Group
 * License: GPL v2 or later
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Define Constants.
defined( 'MBSM_CSM_VERSION' ) || define( 'MBSM_CSM_VERSION', '1.6.0' );
defined( 'MBSM_CSM_PLUGIN_DIR' ) || define( 'MBSM_CSM_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
defined( 'MBSM_CSM_PLUGIN_URL' ) || define( 'MBSM_CSM_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
defined( 'MBSM_CSM_PLUGIN_BASENAME' ) || define( 'MBSM_CSM_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );

/**
 * Main MBSM Comment Spam Moderation Class
 */
class MBSM_CSM_Main {

    /**
     * Single instance of class.
     *
     * @var MBSM_CSM_Main
     */
    private static $instance = null;

    /**
     * Get Instance
     *
     * @return MBSM_CSM_Main
     */
    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_custom_settings' ) ); // Register settings properly
        add_action( 'admin_init', array( $this, 'handle_standard_bulk_actions' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
        
        // AJAX Handler for Smart Clean
        add_action( 'wp_ajax_mbsm_csm_smart_process', array( $this, 'ajax_smart_process' ) );
        
        // Add MBSM Link to Admin Bar
        add_action( 'admin_bar_menu', array( $this, 'add_mbsm_admin_bar_link' ), 999 );
        
        // Plugin Action Links
        add_filter( 'plugin_action_links_' . MBSM_CSM_PLUGIN_BASENAME, array( $this, 'add_plugin_action_links' ) );
    }

    /**
     * Register Settings (For the Editor).
     */
    public function register_custom_settings() {
        register_setting( 'mbsm_csm_settings', 'mbsm_csm_replies_text' );
        register_setting( 'mbsm_csm_settings', 'mbsm_csm_auto_delete' );
    }

    /**
     * Add MBSM Group Link to Admin Bar.
     */
    public function add_mbsm_admin_bar_link( $wp_admin_bar ) {
        $args = array(
            'id'    => 'mbsm_group_link',
            'title' => '<span class="ab-icon" style="margin-top: 3px;">M</span> MBSM Group',
            'href'  => 'https://mbsm.tn/',
            'meta'  => array(
                'title' => esc_html__( 'Visit MBSM Group Official Website', 'mbsm-comment-spam-moderation' ),
                'target' => '_blank',
                'rel'   => 'noopener'
            )
        );
        $wp_admin_bar->add_node( $args );
    }

    /**
     * Add Admin Menu.
     */
    public function add_admin_menu() {
        add_menu_page(
            esc_html__( 'MBSM Moderation', 'mbsm-comment-spam-moderation' ),
            esc_html__( 'MBSM Moderation', 'mbsm-comment-spam-moderation' ),
            'manage_options',
            'mbsm-csm-dashboard',
            array( $this, 'render_dashboard_page' ),
            'dashicons-megaphone',
            30
        );

        add_submenu_page(
            'mbsm-csm-dashboard',
            esc_html__( 'Moderation Dashboard', 'mbsm-comment-spam-moderation' ),
            esc_html__( 'Dashboard', 'mbsm-comment-spam-moderation' ),
            'manage_options',
            'mbsm-csm-dashboard',
            array( $this, 'render_dashboard_page' )
        );
        
        add_submenu_page(
            'mbsm-csm-dashboard',
            esc_html__( 'Updates', 'mbsm-comment-spam-moderation' ),
            esc_html__( 'Updates', 'mbsm-comment-spam-moderation' ),
            'manage_options',
            'mbsm-csm-updates',
            array( $this, 'render_updates_page' )
        );

        add_submenu_page(
            'mbsm-csm-dashboard',
            esc_html__( 'Settings', 'mbsm-comment-spam-moderation' ),
            esc_html__( 'Settings', 'mbsm-comment-spam-moderation' ),
            'manage_options',
            'mbsm-csm-settings',
            array( $this, 'render_settings_page' )
        );
    }

    /**
     * Add Plugin Action Links.
     */
    public function add_plugin_action_links( $links ) {
        $settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=mbsm-csm-settings' ) ) . '">' . esc_html__( 'Settings', 'mbsm-comment-spam-moderation' ) . '</a>';
        $updates_link   = '<a href="' . esc_url( admin_url( 'admin.php?page=mbsm-csm-updates' ) ) . '">' . esc_html__( 'Updates', 'mbsm-comment-spam-moderation' ) . '</a>';
        
        array_unshift( $links, $settings_link );
        array_unshift( $links, $updates_link );
        
        return $links;
    }

    /**
     * Handle Standard Bulk Actions (Approve, Delete, Spam).
     */
    public function handle_standard_bulk_actions() {
        if ( ! isset( $_POST['mbsm_csm_standard_action'] ) || ! isset( $_POST['mbsm_csm_nonce'] ) ) {
            return;
        }

        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mbsm_csm_nonce'] ) ), 'mbsm_csm_bulk_action' ) ) {
            return;
        }

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

        $action = sanitize_text_field( $_POST['mbsm_csm_standard_action'] );
        $comment_ids = isset( $_POST['mbsm_csm_ids'] ) ? array_map( 'intval', $_POST['mbsm_csm_ids'] ) : array();

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

        $count = 0;
        foreach ( $comment_ids as $comment_id ) {
            switch ( $action ) {
                case 'approve':
                    wp_set_comment_status( $comment_id, 'approve' );
                    $count++;
                    break;
                case 'spam':
                    wp_set_comment_status( $comment_id, 'spam' );
                    $count++;
                    break;
                case 'delete':
                    wp_delete_comment( $comment_id, true ); 
                    $count++;
                    break;
            }
        }

        $redirect_url = add_query_arg( array(
            'page' => 'mbsm-csm-dashboard',
            'mbsm_msg' => $count . ' comments processed successfully.'
        ), admin_url( 'admin.php' ) );
        
        wp_safe_redirect( $redirect_url );
        exit;
    }

    /**
     * AJAX Handler: Smart Process (Clean, Replace Name, Approve)
     */
    public function ajax_smart_process() {
        // Security Check
        check_ajax_referer( 'mbsm_csm_smart_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( esc_html__( 'Permission denied.', 'mbsm-comment-spam-moderation' ) );
        }

        // Decode JSON
        $ids_string = isset( $_POST['ids'] ) ? sanitize_text_field( wp_unslash( $_POST['ids'] ) ) : '';
        $comment_ids = json_decode( $ids_string, true );

        if ( ! is_array( $comment_ids ) ) {
            wp_send_json_error( esc_html__( 'Invalid data format.', 'mbsm-comment-spam-moderation' ) );
        }

        $comment_ids = array_map( 'intval', $comment_ids );

        if ( empty( $comment_ids ) ) {
            wp_send_json_error( esc_html__( 'No valid comment IDs.', 'mbsm-comment-spam-moderation' ) );
        }

        // --- Load Replies (Priority: Settings > JSON File) ---
        $replies = array();
        
        // 1. Try to get from WP Options (Editor)
        $saved_replies_text = get_option( 'mbsm_csm_replies_text', '' );
        if ( ! empty( $saved_replies_text ) ) {
            // Split by newline and filter empty lines
            $replies = array_filter( array_map( 'trim', explode( "\n", $saved_replies_text ) ) );
        }

        // 2. Fallback: Load from comments.json file
        if ( empty( $replies ) ) {
            $json_path = MBSM_CSM_PLUGIN_DIR . 'comments.json';
            if ( file_exists( $json_path ) ) {
                $json_content = file_get_contents( $json_path );
                $replies = json_decode( $json_content, true );
            }
        }
        // --- Safe Names for Author Replacement ---
$safe_names = array(
    // English / Western names
    'James', 'Mary', 'John', 'Patricia', 'Robert', 'Jennifer', 'Michael', 'Linda',
    'William', 'Elizabeth', 'David', 'Susan', 'Richard', 'Jessica', 'Joseph', 'Sarah',
    'Thomas', 'Karen', 'Charles', 'Nancy', 'Christopher', 'Lisa', 'Daniel', 'Betty',
    'Matthew', 'Margaret', 'Anthony', 'Sandra', 'Donald', 'Ashley', 'Mark', 'Kimberly',
    'Paul', 'Emily', 'Steven', 'Donna', 'Andrew', 'Michelle', 'Kenneth', 'Carol',
    'Joshua', 'Amanda', 'George', 'Melissa', 'Kevin', 'Deborah', 'Brian', 'Stephanie',
    'Edward', 'Rebecca', 'Ronald', 'Laura', 'Timothy', 'Helen', 'Jason', 'Sharon',
    'Jeffrey', 'Cynthia', 'Ryan', 'Kathleen', 'Jacob', 'Amy', 'Gary', 'Shirley',
    'Nicholas', 'Angela', 'Eric', 'Anna', 'Stephen', 'Ruth', 'Jonathan', 'Brenda',
    'Larry', 'Pamela', 'Justin', 'Nicole', 'Scott', 'Katherine', 'Brandon', 'Samantha',
    'Frank', 'Christine', 'Benjamin', 'Catherine', 'Gregory', 'Virginia', 'Samuel', 'Debra',
    'Raymond', 'Rachel', 'Patrick', 'Janet', 'Alexander', 'Emma', 'Jack', 'Megan',
    
    // Arabic / Middle Eastern names
    'Ahmed', 'Fatima', 'Mohammed', 'Aisha', 'Ali', 'Layla', 'Hassan', 'Noor',
    'Omar', 'Huda', 'Yusuf', 'Amira', 'Khalid', 'Zainab', 'Mahmoud', 'Mariam',
    'Tariq', 'Salma', 'Bilal', 'Rania', 'Saif', 'Nadia', 'Hussein', 'Dalia',
    'Rashid', 'Samira', 'Jamal', 'Mona', 'Faisal', 'Iman', 'Nasser', 'Hanan',
    'Majid', 'Rima', 'Anwar', 'Lina', 'Walid', 'Sara', 'Samir', 'Hind',
    
    // Additional international names
    'Luca', 'Sofia', 'Mario', 'Elena', 'Carlos', 'Maria', 'Juan', 'Carmen',
    'Ivan', 'Olga', 'Dmitri', 'Anastasia', 'Wei', 'Li', 'Min', 'Jin',
    'Kenji', 'Yuki', 'Priya', 'Raj', 'Kim', 'Jihoon', 'Ahmed', 'Zara'
);
// Total count = 150 names

        $processed = array();
        $errors = array();

        foreach ( $comment_ids as $cid ) {
            $comment = get_comment( $cid );
            if ( ! $comment ) {
                $errors[] = "Comment ID $cid not found.";
                continue;
            }

            // Step 1: Generate a Safe Random Name
            $random_name_key = array_rand( $safe_names );
            $new_author_name = $safe_names[ $random_name_key ];

            // Step 2: Generate Random Content
            $random_content_key = array_rand( $replies );
            $new_content = sanitize_textarea_field( $replies[ $random_content_key ] );

            $updated_data = array(
                'comment_ID' => $cid,
                'comment_author' => $new_author_name, // REPLACE NAME
                'comment_author_url' => '',            // DELETE LINK
                'comment_content' => $new_content,     // REPLACE CONTENT
                'comment_approved' => 1,              // APPROVE
            );

            $result = wp_update_comment( $updated_data );

            if ( ! is_wp_error( $result ) ) {
                $processed[] = $cid;
            } else {
                $errors[] = "Failed to update Comment ID $cid.";
            }
        }

        wp_send_json_success( array(
            'processed' => $processed,
            'errors' => $errors
        ) );
    }

    /**
     * Render Dashboard Page.
     */
    public function render_dashboard_page() {
        if ( isset( $_GET['mbsm_msg'] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $_GET['mbsm_msg'] ) . '</p></div>';
        }

        // Get Status Filter
        $status = isset( $_GET['comment_status'] ) ? sanitize_text_field( $_GET['comment_status'] ) : 'hold';
        if ( ! in_array( $status, array( 'hold', 'spam' ) ) ) {
            $status = 'hold';
        }

        // Pagination & Per Page Filter
        $paged = isset( $_GET['cpage'] ) ? max( 1, intval( $_GET['cpage'] ) ) : 1;
        
        // Handle Per Page Logic
        $per_page_options = array( 20, 50, 100, 200 );
        $per_page = isset( $_GET['mbsm_per_page'] ) ? intval( $_GET['mbsm_per_page'] ) : 20;
        if ( $per_page > 200 ) $per_page = 200; 

        // Fetch Comments
        $args = array(
            'status'  => $status,
            'number'  => $per_page,
            'offset'  => ( $paged - 1 ) * $per_page,
            'orderby' => 'comment_date',
            'order'   => 'DESC',
        );
        
        $comments_query = new WP_Comment_Query;
        $comments = $comments_query->query( $args );
        
        // Count total
        $total_comments = get_comments(array(
            'status' => $status,
            'count'  => true,
            'fields' => 'ids'
        ));
        
        $total_pages = ceil( $total_comments / $per_page );

        ?>
        <div class="wrap mbsm-csm-wrap">
            <h1><?php esc_html_e( 'MBSM Comment Moderation', 'mbsm-comment-spam-moderation' ); ?></h1>
            
            <!-- Safety & Tech Notice -->
            <div class="notice notice-info inline" style="margin-bottom: 20px;">
                <p><strong><?php esc_html_e( 'Security & Protocol Notice:', 'mbsm-comment-spam-moderation' ); ?></strong></p>
                <ul style="list-style: disc; margin-left: 20px;">
                    <li><?php esc_html_e( 'Protected by MBSM Group Security Protocols: CSRF Nonces, Admin Capabilities Check, and Input Sanitization are active.', 'mbsm-comment-spam-moderation' ); ?></li>
                    <li><?php esc_html_e( 'Smart Cleaning: Author names will be replaced with generic safe names (e.g., Guest, Reader) to prevent keyword spam.', 'mbsm-comment-spam-moderation' ); ?></li>
                    <li><?php esc_html_e( 'Editor Mode: You can now customize replies easily in the Settings page!', 'mbsm-comment-spam-moderation' ); ?></li>
                </ul>
            </div>

            <hr class="wp-header-end">

            <h2 class="nav-tab-wrapper">
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=mbsm-csm-dashboard&comment_status=hold' ) ); ?>" 
                   class="nav-tab <?php echo $status === 'hold' ? 'nav-tab-active' : ''; ?>">
                   <?php esc_html_e( 'Pending', 'mbsm-comment-spam-moderation' ); ?>
                </a>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=mbsm-csm-dashboard&comment_status=spam' ) ); ?>" 
                   class="nav-tab <?php echo $status === 'spam' ? 'nav-tab-active' : ''; ?>">
                   <?php esc_html_e( 'Spam', 'mbsm-comment-spam-moderation' ); ?>
                </a>
            </h2>

            <form method="post" id="mbsm-csm-form">
                <?php wp_nonce_field( 'mbsm_csm_bulk_action', 'mbsm_csm_nonce' ); ?>
                
                <div class="tablenav top">
                    
                    <!-- Bulk Actions -->
                    <div class="alignleft actions bulkactions">
                        <select name="mbsm_csm_standard_action" id="bulk-action-selector-top">
                            <option value="-1"><?php esc_html_e( 'Bulk Actions', 'mbsm-comment-spam-moderation' ); ?></option>
                            <option value="approve"><?php esc_html_e( 'Approve (Original)', 'mbsm-comment-spam-moderation' ); ?></option>
                            <option value="spam"><?php esc_html_e( 'Mark as Spam', 'mbsm-comment-spam-moderation' ); ?></option>
                            <option value="delete"><?php esc_html_e( 'Delete Permanently', 'mbsm-comment-spam-moderation' ); ?></option>
                        </select>
                        <input type="submit" name="doaction" id="doaction" class="button action" value="<?php esc_attr_e( 'Apply', 'mbsm-comment-spam-moderation' ); ?>">
                        
                        <span class="mbsm-separator" style="display:inline-block; margin: 0 10px; border-right:1px solid #ccc; height:24px; vertical-align:middle;"></span>

                        <!-- Smart Clean Button -->
                        <button type="button" id="mbsm-smart-process-btn" class="button button-primary" style="background-color: #2271b1; color: white;">
                            <?php esc_html_e( 'Smart Clean & Approve', 'mbsm-comment-spam-moderation' ); ?>
                        </button>
                    </div>

                    <!-- Per Page Filter -->
                    <div class="alignleft actions" style="margin-left: 10px;">
                        <label for="mbsm-per-page" style="vertical-align: middle;"><?php esc_html_e( 'Show:', 'mbsm-comment-spam-moderation' ); ?></label>
                        <select id="mbsm-per-page" name="mbsm_per_page" style="vertical-align: middle;">
                            <?php foreach ( $per_page_options as $opt ) : ?>
                                <option value="<?php echo esc_attr( $opt ); ?>" <?php selected( $per_page, $opt ); ?>><?php echo esc_html( $opt ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <?php $this->render_pagination( $paged, $total_pages, $status ); ?>
                    
                    <br class="clear">
                </div>

                <!-- Live Log Box -->
                <div id="mbsm-log-container" style="display:none; background: #fff; border: 1px solid #c3c4c7; padding: 15px; margin: 20px 0; height: 200px; overflow-y: scroll; font-family: monospace; font-size: 13px;">
                    <strong><?php esc_html_e( 'Processing Log:', 'mbsm-comment-spam-moderation' ); ?></strong>
                    <ul id="mbsm-log-list" style="list-style: none; margin: 0; padding: 0;"></ul>
                </div>

                <table class="wp-list-table widefat fixed striped comments">
                    <thead>
                        <tr>
                            <td class="manage-column column-cb check-column">
                                <label class="screen-reader-text"><?php esc_html_e( 'Select All', 'mbsm-comment-spam-moderation' ); ?></label>
                                <input type="checkbox" id="mbsm-select-all">
                            </td>
                            <th scope="col" class="manage-column column-author"><?php esc_html_e( 'Author', 'mbsm-comment-spam-moderation' ); ?></th>
                            <th scope="col" class="manage-column column-comment"><?php esc_html_e( 'Comment', 'mbsm-comment-spam-moderation' ); ?></th>
                            <th scope="col" class="manage-column column-response"><?php esc_html_e( 'In Response To', 'mbsm-comment-spam-moderation' ); ?></th>
                            <th scope="col" class="manage-column column-date"><?php esc_html_e( 'Submitted On', 'mbsm-comment-spam-moderation' ); ?></th>
                        </tr>
                    </thead>

                    <tbody id="the-comment-list" data-wp-lists="list:comment">
                        <?php if ( ! empty( $comments ) ) : ?>
                            <?php foreach ( $comments as $comment ) : ?>
                                <tr id="comment-<?php echo esc_attr( $comment->comment_ID ); ?>">
                                    <th class="check-column">
                                        <input type="checkbox" name="mbsm_csm_ids[]" value="<?php echo esc_attr( $comment->comment_ID ); ?>" class="mbsm-comment-cb">
                                    </th>
                                    <td class="author column-author">
                                        <?php echo get_avatar( $comment, 32 ); ?>
                                        <strong><?php echo esc_html( $comment->comment_author ); ?></strong><br>
                                        <?php comment_author_email_link( '', '<br>', '', $comment->comment_ID ); ?>
                                        <?php if ( ! empty( $comment->comment_author_url ) ) : ?>
                                            <br>
                                            <a href="<?php echo esc_url( $comment->comment_author_url ); ?>" target="_blank" rel="noopener noreferrer" title="<?php echo esc_attr( $comment->comment_author_url ); ?>">
                                                <?php echo esc_html( $comment->comment_author_url ); ?>
                                            </a>
                                        <?php endif; ?>
                                    </td>
                                    <td class="comment column-comment">
                                        <div class="comment-content">
                                            <?php echo wp_kses_post( $comment->comment_content ); ?>
                                        </div>
                                        <p>
                                            <a href="<?php echo esc_url( admin_url( 'comment.php?action=editcomment&c=' . $comment->comment_ID ) ); ?>" target="_blank" rel="noopener" title="<?php esc_attr_e( 'Edit Comment', 'mbsm-comment-spam-moderation' ); ?>">
                                                <?php esc_html_e( 'Edit', 'mbsm-comment-spam-moderation' ); ?>
                                            </a> | 
                                            <a href="<?php echo esc_url( admin_url( 'comment.php?action=deletecomment&c=' . $comment->comment_ID . '&_wpnonce=' . wp_create_nonce( 'delete-comment_' . $comment->comment_ID ) ) ); ?>" title="<?php esc_attr_e( 'Delete this comment', 'mbsm-comment-spam-moderation' ); ?>">
                                                <?php esc_html_e( 'Delete', 'mbsm-comment-spam-moderation' ); ?>
                                            </a>
                                        </p>
                                    </td>
                                    <td class="response column-response">
                                        <?php if ( $comment->comment_post_ID > 0 ) : ?>
                                            <a href="<?php echo esc_url( get_permalink( $comment->comment_post_ID ) ); ?>" target="_blank" rel="noopener" title="<?php echo esc_attr( get_the_title( $comment->comment_post_ID ) ); ?>">
                                                <?php echo esc_html( get_the_title( $comment->comment_post_ID ) ); ?>
                                            </a>
                                        <?php else : ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td class="date column-date">
                                        <?php 
                                            $date_time = mysql2date( __( 'Y/m/d \a\t g:i a' ), $comment->comment_date );
                                            echo esc_html( $date_time ); 
                                        ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else : ?>
                            <tr>
                                <td colspan="5"><?php esc_html_e( 'No comments found.', 'mbsm-comment-spam-moderation' ); ?></td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>

                <div class="tablenav bottom">
                    <?php $this->render_pagination( $paged, $total_pages, $status ); ?>
                    <br class="clear">
                </div>
            </form>

            <!-- MBSM Admin Footer -->
            <div class="mbsm-admin-footer" style="margin-top: 40px; padding-top: 20px; border-top: 1px solid #e5e5e5; text-align: center; color: #666; font-size: 13px;">
                <p>
                    &copy; <?php echo esc_html( date( 'Y' ) ); ?> <strong>MBSM Group</strong>. All rights reserved.
                </p>
                <p>
                    <a href="https://mbsm.tn/" target="_blank" rel="noopener" title="MBSM Pro Official Website">MBSM Pro</a> | 
                    <a href="https://www.mbsm.tn/" target="_blank" rel="noopener" title="MBSM Group Official Website">MBSM Group</a> | 
                    <a href="https://mbsm.tn/support" target="_blank" rel="noopener" title="MBSM Support">Support</a>
                </p>
                <p style="font-size: 11px; color: #999;">
                    <?php esc_html_e( 'Powered by JSON Reader Protocol & MBSM Secure Technology.', 'mbsm-comment-spam-moderation' ); ?>
                </p>
            </div>
        </div>

        <script type="text/javascript">
            // Per Page Filter Logic
            document.getElementById('mbsm-per-page').addEventListener('change', function(e) {
                var url = new URL(window.location.href);
                url.searchParams.set('mbsm_per_page', e.target.value);
                url.searchParams.set('cpage', 1); 
                window.location.href = url;
            });

            // Select All / Deselect All
            document.getElementById('mbsm-select-all').addEventListener('change', function(e) {
                var checkboxes = document.querySelectorAll('input[name="mbsm_csm_ids[]"]');
                checkboxes.forEach(function(chk) {
                    chk.checked = e.target.checked;
                });
            });

            // Smart Process Logic (AJAX Batching + Live Refresh)
            document.getElementById('mbsm-smart-process-btn').addEventListener('click', function(e) {
                e.preventDefault();

                var checkboxes = document.querySelectorAll('input[name="mbsm_csm_ids[]"]:checked');
                var ids = Array.from(checkboxes).map(function(chk) { return chk.value; });

                if (ids.length === 0) {
                    alert('<?php esc_html_e( 'Please select at least one comment.', 'mbsm-comment-spam-moderation' ); ?>');
                    return;
                }

                if (!confirm('<?php esc_html_e( 'This will replace comment content, replace author name, remove links, and approve. Continue?', 'mbsm-comment-spam-moderation' ); ?>')) {
                    return;
                }

                // Prepare UI
                var logContainer = document.getElementById('mbsm-log-container');
                var logList = document.getElementById('mbsm-log-list');
                logContainer.style.display = 'block';
                logList.innerHTML = '';
                e.target.disabled = true;

                var batchSize = 20; 
                var batches = [];
                for (var i = 0; i < ids.length; i += batchSize) {
                    batches.push(ids.slice(i, i + batchSize));
                }

                var currentBatch = 0;
                var totalProcessed = 0;

                function processBatch() {
                    if (currentBatch >= batches.length) {
                        e.target.disabled = false;
                        e.target.textContent = '<?php esc_html_e( 'Done!', 'mbsm-comment-spam-moderation' ); ?>';
                        var li = document.createElement('li');
                        li.textContent = 'FINISHED: ' + totalProcessed + ' comments processed.';
                        li.style.color = 'green';
                        li.style.fontWeight = 'bold';
                        logList.appendChild(li);
                        logContainer.scrollTop = logContainer.scrollHeight;
                        return;
                    }

                    var batchIds = batches[currentBatch];
                    
                    var liStart = document.createElement('li');
                    liStart.textContent = 'Processing batch ' + (currentBatch + 1) + ' of ' + batches.length + '...';
                    liStart.style.color = '#0073aa';
                    logList.appendChild(liStart);

                    var idsJson = JSON.stringify(batchIds);

                    fetch('<?php echo admin_url( 'admin-ajax.php' ); ?>', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: new URLSearchParams({
                            action: 'mbsm_csm_smart_process',
                            nonce: '<?php echo wp_create_nonce( 'mbsm_csm_smart_nonce' ); ?>',
                            ids: idsJson
                        })
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('HTTP error! status: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            totalProcessed += data.data.processed.length;
                            
                            var liSuccess = document.createElement('li');
                            liSuccess.textContent = 'Batch ' + (currentBatch + 1) + ' Done. Processed: ' + data.data.processed.length;
                            liSuccess.style.color = 'green';
                            logList.appendChild(liSuccess);

                            if (data.data.errors.length > 0) {
                                var liError = document.createElement('li');
                                liError.textContent = 'Errors: ' + data.data.errors.join(', ');
                                liError.style.color = 'red';
                                logList.appendChild(liError);
                            }

                            // --- SMART REFRESH: Remove Rows Immediately ---
                            batchIds.forEach(function(id) {
                                var row = document.getElementById('comment-' + id);
                                if (row) {
                                    row.style.background = '#d4edda';
                                    setTimeout(function() {
                                        row.remove();
                                    }, 300); 
                                }
                            });
                            // ------------------------------------------------

                        } else {
                            var liFail = document.createElement('li');
                            liFail.textContent = 'Server Logic Error: ' + (data.data || 'Unknown');
                            liFail.style.color = 'red';
                            logList.appendChild(liFail);
                        }
                        
                        logContainer.scrollTop = logContainer.scrollHeight;
                        currentBatch++;
                        setTimeout(processBatch, 500); 
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        var liCatch = document.createElement('li');
                        liCatch.textContent = 'Connection Error in batch ' + (currentBatch + 1) + ': ' + error.message;
                        liCatch.style.color = 'red';
                        logList.appendChild(liCatch);
                        currentBatch++;
                        setTimeout(processBatch, 1000); 
                    });
                }

                processBatch();
            });
        </script>
        <?php
    }

    /**
     * Render Pagination.
     */
    private function render_pagination( $current, $total, $status ) {
        if ( $total <= 1 ) return;

        $big = 999999999;
        
        // Get current per page to maintain it in links
        $per_page = isset( $_GET['mbsm_per_page'] ) ? intval( $_GET['mbsm_per_page'] ) : 20;
        
        $args = array(
            'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
            'format'    => '?cpage=%#%',
            'total'     => $total,
            'current'   => $current,
            'add_args'  => array( 
                'comment_status' => $status,
                'mbsm_per_page' => $per_page 
            ),
            'prev_text' => esc_html__( '&laquo; Prev', 'mbsm-comment-spam-moderation' ),
            'next_text' => esc_html__( 'Next &raquo;', 'mbsm-comment-spam-moderation' ),
            'type'      => 'plain',
        );

        $pagination = paginate_links( $args );
        
        if ( $pagination ) {
            echo '<div class="tablenav-pages"><span class="displaying-num">' . esc_html( $total ) . ' items</span>' . $pagination . '</div>';
        }
    }
    
    /**
     * Render Updates Page.
     */
    public function render_updates_page() {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'MBSM Updates', 'mbsm-comment-spam-moderation' ); ?></h1>
            <div class="card" style="max-width: 600px; padding: 20px;">
                <h2><?php esc_html_e( 'Plugin Updates', 'mbsm-comment-spam-moderation' ); ?></h2>
                <p><?php esc_html_e( 'Current Version:', 'mbsm-comment-spam-moderation' ); ?> <strong><?php echo esc_html( MBSM_CSM_VERSION ); ?></strong></p>
                <p><?php esc_html_e( 'You are using the latest stable version of MBSM Comment Moderation.', 'mbsm-comment-spam-moderation' ); ?></p>
                <a href="https://mbsm.tn/" target="_blank" rel="noopener" title="Check for updates on MBSM Pro" class="button"><?php esc_html_e( 'Check for Updates', 'mbsm-comment-spam-moderation' ); ?></a>
            </div>
        </div>
        <?php
    }

    /**
     * Render Settings Page (With Editor).
     */
    public function render_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'MBSM Settings', 'mbsm-comment-spam-moderation' ); ?></h1>
            <form action="options.php" method="post">
                <?php
                settings_fields( 'mbsm_csm_settings' );
                do_settings_sections( 'mbsm-csm-settings' );
                ?>
                
                <table class="form-table">
                    <tr valign="top">
                        <th scope="row"><?php esc_html_e( 'Auto-Delete Spam', 'mbsm-comment-spam-moderation' ); ?></th>
                        <td>
                            <input type="checkbox" name="mbsm_csm_auto_delete" value="1" <?php checked( get_option( 'mbsm_csm_auto_delete' ), 1 ); ?> />
                            <label><?php esc_html_e( 'Automatically delete spam older than 30 days', 'mbsm-comment-spam-moderation' ); ?></label>
                        </td>
                    </tr>

                    <!-- Smart Replies Editor -->
                    <tr valign="top">
                        <th scope="row">
                            <?php esc_html_e( 'Smart Replies Editor', 'mbsm-comment-spam-moderation' ); ?>
                            <br><span style="font-size: 12px; color: #666;">(One reply per line)</span>
                        </th>
                        <td>
                            <textarea name="mbsm_csm_replies_text" rows="20" cols="50" class="large-text code" style="width: 600px; font-family: monospace;"><?php echo esc_textarea( get_option( 'mbsm_csm_replies_text' ) ); ?></textarea>
                            <p class="description">
                                <?php esc_html_e( 'Edit the list of replies used by the Smart Clean feature. Each line represents a possible reply.', 'mbsm-comment-spam-moderation' ); ?>
                            </p>
                        </td>
                    </tr>

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

    /**
     * Enqueue Scripts.
     */
    public function enqueue_admin_assets( $hook ) {
        // No external assets needed.
    }
}

// Initialize Plugin.
MBSM_CSM_Main::get_instance();