<?php
/**
 * Plugin Name: MBSM Comment Spam Moderation
 * Plugin URI: https://www.mbsmpro.com/
 * Description: Advanced comment moderation tool by MBSM Group. Features Smart Clean, Name Replacement, Live Table Refresh, and full security protocols.
 * Version: 1.5.1
 * 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.5.1' );
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__ ) );
defined( 'MBSM_CSM_CACHE_TIME' ) || define( 'MBSM_CSM_CACHE_TIME', HOUR_IN_SECONDS );

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

    private static $instance = null;
    private $cached_replies = null;

    public static function get_instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_init', array( $this, 'handle_standard_bulk_actions' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
        add_action( 'wp_ajax_mbsm_csm_smart_process', array( $this, 'ajax_smart_process' ) );
        add_action( 'admin_bar_menu', array( $this, 'add_mbsm_admin_bar_link' ), 999 );
        add_filter( 'plugin_action_links_' . MBSM_CSM_PLUGIN_BASENAME, array( $this, 'add_plugin_action_links' ) );
        register_activation_hook( __FILE__, array( $this, 'activate_plugin' ) );
    }

    public function activate_plugin() {
        add_option( 'mbsm_csm_auto_delete', 0 );
        global $wpdb;
        $table = $wpdb->comments;
        $index = 'comment_approved_date';
        $existing = $wpdb->get_results( "SHOW INDEX FROM {$table} WHERE Key_name = '{$index}'" );
        if ( empty( $existing ) ) {
            $wpdb->query( "ALTER TABLE {$table} ADD INDEX {$index} (comment_approved, comment_date_gmt)" );
        }
    }

    public function register_settings() {
        register_setting( 'mbsm_csm_settings', 'mbsm_csm_auto_delete', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 0,
        ) );
    }

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

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

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

    public function handle_standard_bulk_actions() {
        if ( ! isset( $_POST['mbsm_csm_standard_action'], $_POST['mbsm_csm_nonce'] ) ) return;
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mbsm_csm_nonce'] ) ), 'mbsm_csm_bulk_action' ) ) wp_die( esc_html__( 'Security check failed.', 'mbsm-comment-spam-moderation' ), '', array( 'response' => 403 ) );
        if ( ! current_user_can( 'manage_options' ) ) wp_die( esc_html__( 'Insufficient permissions.', 'mbsm-comment-spam-moderation' ), '', array( 'response' => 403 ) );

        $action = sanitize_text_field( $_POST['mbsm_csm_standard_action'] );
        $comment_ids = isset( $_POST['mbsm_csm_ids'] ) ? array_map( 'intval', (array) $_POST['mbsm_csm_ids'] ) : array();
        if ( empty( $comment_ids ) || '-1' === $action ) return;

        $count = 0;
        foreach ( $comment_ids as $cid ) {
            $result = false;
            if ( 'approve' === $action ) $result = wp_set_comment_status( $cid, 'approve' );
            elseif ( 'spam' === $action ) $result = wp_set_comment_status( $cid, 'spam' );
            elseif ( 'delete' === $action ) $result = wp_delete_comment( $cid, true );
            if ( $result ) $count++;
        }

        wp_safe_redirect( add_query_arg( array( 'page' => 'mbsm-csm-dashboard', 'mbsm_msg' => sprintf( _n( '%d comment processed successfully.', '%d comments processed successfully.', $count, 'mbsm-comment-spam-moderation' ), $count ) ), admin_url( 'admin.php' ) ) );
        exit;
    }

    private function load_replies() {
        if ( null !== $this->cached_replies ) return $this->cached_replies;
        $cache_key = 'mbsm_csm_replies_v' . MBSM_CSM_VERSION;
        $replies = wp_cache_get( $cache_key, 'mbsm_csm' );
        if ( false === $replies ) {
            $json_path = MBSM_CSM_PLUGIN_DIR . 'comments.json';
            if ( file_exists( $json_path ) && is_readable( $json_path ) ) {
                $content = file_get_contents( $json_path );
                $replies = json_decode( $content, true );
                if ( is_array( $replies ) && ! empty( $replies ) ) wp_cache_set( $cache_key, $replies, 'mbsm_csm', MBSM_CSM_CACHE_TIME );
            }
        }
        if ( ! is_array( $replies ) || empty( $replies ) ) {
            $replies = array( esc_html__( 'Thank you for your comment!', 'mbsm-comment-spam-moderation' ), esc_html__( 'We appreciate your feedback.', 'mbsm-comment-spam-moderation' ), esc_html__( 'Your input helps us improve.', 'mbsm-comment-spam-moderation' ) );
        }
        $this->cached_replies = $replies;
        return $replies;
    }

    private function get_safe_names() {
        static $safe_names = null;
        if ( null !== $safe_names ) return $safe_names;
        $safe_names = array( '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','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','Luca','Sofia','Mario','Elena','Carlos','Maria','Juan','Carmen','Ivan','Olga','Dmitri','Anastasia','Wei','Li','Min','Jin','Kenji','Yuki','Priya','Raj','Kim','Jihoon','Zara' );
        $safe_names = array_values( array_unique( $safe_names ) );
        return $safe_names;
    }

    public function ajax_smart_process() {
        check_ajax_referer( 'mbsm_csm_smart_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => esc_html__( 'Permission denied.', 'mbsm-comment-spam-moderation' ) ), 403 );

        $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( array( 'message' => esc_html__( 'Invalid data format.', 'mbsm-comment-spam-moderation' ) ), 400 );
        $comment_ids = array_filter( array_map( 'intval', $comment_ids ) );
        if ( empty( $comment_ids ) ) wp_send_json_error( array( 'message' => esc_html__( 'No valid comment IDs.', 'mbsm-comment-spam-moderation' ) ), 400 );

        $replies = $this->load_replies();
        $safe_names = $this->get_safe_names();
        $processed = array(); $errors = array();

        foreach ( $comment_ids as $cid ) {
            $comment = get_comment( $cid );
            if ( ! $comment ) { $errors[] = sprintf( esc_html__( 'Comment ID %d not found.', 'mbsm-comment-spam-moderation' ), $cid ); continue; }
            $new_author_name = $safe_names[ array_rand( $safe_names ) ];
            $new_content = sanitize_textarea_field( $replies[ array_rand( $replies ) ] );
            $updated_data = array( 'comment_ID' => $cid, 'comment_author' => $new_author_name, 'comment_author_url' => '', 'comment_content' => $new_content, 'comment_approved' => '1' );
            $result = wp_update_comment( $updated_data, true );
            if ( 1 === $result || true === $result ) { $processed[] = $cid; clean_comment_cache( $cid ); }
            else { $errors[] = sprintf( esc_html__( 'Failed to update Comment ID %d.', 'mbsm-comment-spam-moderation' ), $cid ); }
        }
        wp_send_json_success( array( 'processed' => $processed, 'errors' => $errors, 'count' => count( $processed ) ) );
    }

    public function render_dashboard_page() {
        if ( isset( $_GET['mbsm_msg'] ) ) echo '<div class="notice notice-success is-dismissible"><p>' . wp_kses_post( wp_unslash( $_GET['mbsm_msg'] ) ) . '</p></div>';
        if ( isset( $_GET['mbsm_error'] ) ) echo '<div class="notice notice-error is-dismissible"><p>' . wp_kses_post( wp_unslash( $_GET['mbsm_error'] ) ) . '</p></div>';

        $status = isset( $_GET['comment_status'] ) ? sanitize_text_field( $_GET['comment_status'] ) : 'hold';
        if ( ! in_array( $status, array( 'hold', 'spam' ), true ) ) $status = 'hold';
        $paged = isset( $_GET['cpage'] ) ? max( 1, intval( $_GET['cpage'] ) ) : 1;
        $per_page_options = array( 20, 50, 100, 200 );
        $per_page = isset( $_GET['mbsm_per_page'] ) ? intval( $_GET['mbsm_per_page'] ) : 20;
        $per_page = in_array( $per_page, $per_page_options, true ) ? $per_page : 20;

        $comments = get_comments( array( 'status' => $status, 'number' => $per_page, 'offset' => ( $paged - 1 ) * $per_page, 'orderby' => 'comment_date_gmt', 'order' => 'DESC' ) );
        $total_comments = get_comments( array( 'status' => $status, 'count' => true, 'fields' => 'ids' ) );
        $total_pages = ceil( $total_comments / $per_page );

        $post_ids = array_filter( wp_list_pluck( $comments, 'comment_post_ID' ) );
        $post_titles = array();
        if ( ! empty( $post_ids ) ) {
            $post_titles = get_posts( array( 'post__in' => $post_ids, 'fields' => 'id=>title', 'suppress_filters' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false ) );
        }
        ?>
        <div class="wrap mbsm-csm-wrap">
            <h1><?php esc_html_e( 'MBSM Comment Moderation', 'mbsm-comment-spam-moderation' ); ?></h1>
            <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 to prevent keyword spam.', 'mbsm-comment-spam-moderation' ); ?></li>
                    <li><?php esc_html_e( 'Optimized Performance: JSON caching, batched AJAX processing, and database indexing enabled.', 'mbsm-comment-spam-moderation' ); ?></li>
                </ul>
            </div>
            <hr class="wp-header-end">
            <h2 class="nav-tab-wrapper">
                <a href="<?php echo esc_url( add_query_arg( array( 'page'=>'mbsm-csm-dashboard','comment_status'=>'hold','mbsm_per_page'=>$per_page ), admin_url('admin.php') ) ); ?>" 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( add_query_arg( array( 'page'=>'mbsm-csm-dashboard','comment_status'=>'spam','mbsm_per_page'=>$per_page ), admin_url('admin.php') ) ); ?>" 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">
                    <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>
                        <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>
                    <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, $per_page ); ?>
                    <br class="clear">
                </div>
                <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) ): foreach( $comments as $comment ): ?>
                        <tr id="comment-<?php echo esc_attr($comment->comment_ID); ?>" class="<?php echo $comment->comment_approved==='spam'?'spam':''; ?>">
                            <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,'','',array('force_display'=>true,'class'=>'avatar')); ?>
                                <strong><?php echo esc_html($comment->comment_author); ?></strong><br>
                                <?php if($comment->comment_author_email): ?><a href="mailto:<?php echo esc_attr(antispambot($comment->comment_author_email)); ?>"><?php echo esc_html(antispambot($comment->comment_author_email)); ?></a><br><?php endif; ?>
                                <?php if(!empty($comment->comment_author_url)): ?><a href="<?php echo esc_url($comment->comment_author_url); ?>" target="_blank" rel="noopener noreferrer external" title="<?php echo esc_attr($comment->comment_author_url); ?>"><?php echo esc_html(wp_parse_url($comment->comment_author_url,PHP_URL_HOST)); ?></a><?php endif; ?>
                            </td>
                            <td class="comment column-comment">
                                <div class="comment-content"><?php echo wp_kses_post(wp_trim_excerpt($comment->comment_content,20)); ?></div>
                                <p><a href="<?php echo esc_url(admin_url('comment.php?action=editcomment&c='.$comment->comment_ID)); ?>" target="_blank" rel="noopener"><?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))); ?>" class="submitdelete deletion"><?php esc_html_e('Delete','mbsm-comment-spam-moderation'); ?></a></p>
                            </td>
                            <td class="response column-response">
                                <?php if($comment->comment_post_ID>0 && isset($post_titles[$comment->comment_post_ID])): ?>
                                    <a href="<?php echo esc_url(get_permalink($comment->comment_post_ID)); ?>" target="_blank" rel="noopener"><?php echo esc_html(wp_trim_words($post_titles[$comment->comment_post_ID],5,'&hellip;')); ?></a>
                                <?php else: ?><em><?php esc_html_e('Post not found','mbsm-comment-spam-moderation'); ?></em><?php endif; ?>
                            </td>
                            <td class="date column-date"><time datetime="<?php echo esc_attr($comment->comment_date_gmt); ?>"><?php echo esc_html(mysql2date(__('Y/m/d \a\t g:i a','mbsm-comment-spam-moderation'),$comment->comment_date)); ?></time></td>
                        </tr>
                        <?php endforeach; 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,$per_page); ?><br class="clear"></div>
            </form>
            <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>. <?php esc_html_e('All rights reserved.','mbsm-comment-spam-moderation'); ?></p>
                <p><a href="https://www.mbsmpro.com/" target="_blank" rel="noopener">MBSM Pro</a> | <a href="https://www.mbsm.tn/" target="_blank" rel="noopener">MBSM Group</a> | <a href="https://www.mbsmpro.com/support" target="_blank" rel="noopener">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">
        (function($){'use strict';
            $('#mbsm-per-page').on('change',function(){var u=new URL(window.location.href);u.searchParams.set('mbsm_per_page',$(this).val());u.searchParams.set('cpage','1');window.location.href=u.toString();});
            $('#mbsm-select-all').on('change',function(){$('.mbsm-comment-cb').prop('checked',this.checked);});
            $('#mbsm-smart-process-btn').on('click',function(e){e.preventDefault();var $b=$(this),ids=$('input[name="mbsm_csm_ids[]"]:checked').map(function(){return this.value;}).get();if(!ids.length){alert('<?php echo esc_js(__('Please select at least one comment.','mbsm-comment-spam-moderation')); ?>');return;}if(!confirm('<?php echo esc_js(__('This will replace comment content, replace author name, remove links, and approve. Continue?','mbsm-comment-spam-moderation')); ?>'))return;var $lc=$('#mbsm-log-container'),$ll=$('#mbsm-log-list');$lc.show();$ll.empty();$b.prop('disabled',!0).text('<?php echo esc_js(__('Processing...','mbsm-comment-spam-moderation')); ?>');var bs=20,batches=[],i;for(i=0;i<ids.length;i+=bs)batches.push(ids.slice(i,i+bs));var cb=0,tp=0,ajax='<?php echo esc_js(admin_url('admin-ajax.php')); ?>',nc='<?php echo esc_js(wp_create_nonce('mbsm_csm_smart_nonce')); ?>';function pb(){if(cb>=batches.length){$b.prop('disabled',!1).text('<?php echo esc_js(__('Done!','mbsm-comment-spam-moderation')); ?>');$ll.append($('<li>').css({color:'green',fontWeight:'bold'}).text('FINISHED: '+tp+' <?php echo esc_js(__('comments processed.','mbsm-comment-spam-moderation')); ?>'));$lc.scrollTop($lc[0].scrollHeight);setTimeout(function(){window.location.reload();},2000);return;}var bid=batches[cb];$ll.append($('<li>').css('color','#0073aa').text('Processing batch '+(cb+1)+' of '+batches.length+'...'));$.post(ajax,{action:'mbsm_csm_smart_process',nonce:nc,ids:JSON.stringify(bid)}).done(function(r){if(r.success){tp+=r.data.processed.length;$ll.append($('<li>').css('color','green').text('Batch '+(cb+1)+' Done. Processed: '+r.data.processed.length));if(r.data.errors&&r.data.errors.length)$ll.append($('<li>').css('color','red').text('Errors: '+r.data.errors.join(', ')));bid.forEach(function(id){var $r=$('#comment-'+id);if($r.length)$r.fadeOut(200,function(){$(this).remove();});});}else{$ll.append($('<li>').css('color','red').text('Server Error: '+(r.data&&r.data.message?r.data.message:'Unknown')));}$lc.scrollTop($lc[0].scrollHeight);cb++;setTimeout(pb,300);}).fail(function(x,s,e){console.error('AJAX Error:',e);$ll.append($('<li>').css('color','red').text('Connection Error in batch '+(cb+1)+': '+e));cb++;setTimeout(pb,1000);});}pb();});
        })(jQuery);
        </script>
        <?php
    }

    private function render_pagination( $current, $total, $status, $per_page ) {
        if ( $total <= 1 ) return;
        $base = add_query_arg( array( 'page'=>'mbsm-csm-dashboard','comment_status'=>$status,'mbsm_per_page'=>$per_page,'cpage'=>'%#%' ), admin_url('admin.php') );
        $pagination = paginate_links( array( 'base'=>$base,'format'=>'','total'=>$total,'current'=>$current,'prev_text'=>esc_html__('&laquo; Prev','mbsm-comment-spam-moderation'),'next_text'=>esc_html__('Next &raquo;','mbsm-comment-spam-moderation'),'type'=>'plain','add_args'=>false ) );
        if ( $pagination ) echo '<div class="tablenav-pages"><span class="displaying-num">'.sprintf(esc_html(_n('%s item','%s items',$total,'mbsm-comment-spam-moderation')),number_format_i18n($total)).'</span>'.$pagination.'</div>';
    }

    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;margin-top: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://www.mbsmpro.com/" target="_blank" rel="noopener" class="button button-primary"><?php esc_html_e('Check for Updates','mbsm-comment-spam-moderation'); ?></a></div></div><?php
    }

    public function render_settings_page() {
        ?><div class="wrap"><h1><?php esc_html_e('MBSM Settings','mbsm-comment-spam-moderation'); ?></h1><form method="post" action="options.php"><?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><label><input type="checkbox" name="mbsm_csm_auto_delete" value="1" <?php checked(get_option('mbsm_csm_auto_delete'),1); ?>> <?php esc_html_e('Automatically delete spam comments older than 30 days','mbsm-comment-spam-moderation'); ?></label><p class="description"><?php esc_html_e('When enabled, a daily cron job will remove old spam to keep your database clean.','mbsm-comment-spam-moderation'); ?></p></td></tr></table><?php submit_button(); ?></form></div><?php
    }

    public function enqueue_admin_assets( $hook ) {
        if ( false === strpos( $hook, 'mbsm-csm' ) ) return;
        wp_enqueue_script( 'jquery' );
        wp_add_inline_style( 'common', '.mbsm-csm-wrap .column-author img{float:left;margin-right:8px}.mbsm-csm-wrap .comment-content{max-height:80px;overflow:hidden}.mbsm-csm-wrap tr.spam{background-color:#fff8f8}#mbsm-log-container{border-radius:4px;box-shadow:0 1px 3px rgba(0,0,0,.1)}' );
    }
}

MBSM_CSM_Main::get_instance();