<?php
/**
 * Plugin Name: Thia Aide Comment Moderator
 * Description: Automatically moderates comments using Thia Aide AI Comment Moderator
 * Version:     1.0.0
 * Author:      Thia Aide
 * Author URI:  https://www.thiaide.com
 * License:     GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain: thia-aide-comment-moderator
 * Domain Path: /languages
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}

/**
 * Current plugin version.
 */
define( 'THIAIDE_VERSION', '1.0.0' );
define( 'THIAIDE_API_URL', 'https://thiaide.com/api/' );
define( 'THIAIDE_TABLE_NAME', 'thiaide_moderator_api_keys' );
define( 'THIAIDE_BLOCKED_IPS_TABLE', 'thiaide_moderator_blocked_ips' );
define( 'THIAIDE_BLOCKED_USERS_TABLE', 'thiaide_moderator_blocked_users' );
define( 'THIAIDE_WARNINGS_TABLE', 'thiaide_moderator_warnings' );
define( 'THIAIDE_STATSAPI_TABLE', 'thiaide_moderator_api_stats' );
define( 'THIAIDE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'THIAIDE_PLUGIN_URL', plugin_dir_url( __FILE__ ) );

/**
 * Initialize the plugin.
 */
function thia_comment_moderator_init() {
    add_filter( 'pre_comment_approved', 'thia_comment_moderator_check', 10, 2 );
    add_action( 'admin_menu', 'thia_comment_moderator_add_admin_menu' );
    add_action( 'admin_init', 'thia_comment_moderator_check_tables' );
}
add_action( 'init', 'thia_comment_moderator_init' );

/**
 * Plugin activation hook.
 */
register_activation_hook( __FILE__, 'thia_comment_moderator_install' );
function thia_comment_moderator_install() {
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();

    $table_keys = $wpdb->prefix . THIAIDE_TABLE_NAME;
    $sql_keys = "CREATE TABLE IF NOT EXISTS `$table_keys` (
        id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        api_key VARCHAR(255) NOT NULL UNIQUE,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    ) $charset_collate;";

    $table_ips = $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE;
    $sql_ips = "CREATE TABLE IF NOT EXISTS `$table_ips` (
        id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        ip VARCHAR(45) NOT NULL UNIQUE,
        blocked_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_ip (ip)
    ) $charset_collate;";

    $table_users = $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE;
    $sql_users = "CREATE TABLE IF NOT EXISTS `$table_users` (
        id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(255) NOT NULL UNIQUE,
        blocked_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_email (email)
    ) $charset_collate;";

    $table_warnings = $wpdb->prefix . THIAIDE_WARNINGS_TABLE;
    $sql_warnings = "CREATE TABLE IF NOT EXISTS `$table_warnings` (
        id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        ip VARCHAR(45) NOT NULL,
        email VARCHAR(255),
        warning_count INT DEFAULT 1,
        last_warning DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_ip (ip),
        INDEX idx_email (email)
    ) $charset_collate;";
    
    $table_stats = $wpdb->prefix . THIAIDE_STATSAPI_TABLE;
    $sql_stats = "CREATE TABLE IF NOT EXISTS `$table_stats` (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        date date NOT NULL,
        api_calls int(11) DEFAULT 0,
        total_tokens int(11) DEFAULT 0,
        successful_calls int(11) DEFAULT 0,
        failed_calls int(11) DEFAULT 0,
        created datetime DEFAULT CURRENT_TIMESTAMP,
        updated datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY date_unique (date)
    ) $charset_collate;";
    
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange -- Required for plugin installation.
    dbDelta( $sql_keys );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange -- Required for plugin installation.
    dbDelta( $sql_ips );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange -- Required for plugin installation.
    dbDelta( $sql_users );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange -- Required for plugin installation.
    dbDelta( $sql_warnings );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange -- Required for plugin installation.
    dbDelta( $sql_stats );
}

/**
 * Check if a table exists.
 */
function thia_table_exists( $table_name ) {
    global $wpdb;
    $result = $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table_name ) );
    return $result === $table_name;
}

/**
 * Check tables on admin init.
 */
function thia_comment_moderator_check_tables() {
    global $wpdb;
    $tables = [
        $wpdb->prefix . THIAIDE_TABLE_NAME,
        $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE,
        $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE,
        $wpdb->prefix . THIAIDE_WARNINGS_TABLE,
        $wpdb->prefix . THIAIDE_STATSAPI_TABLE,
    ];

    foreach ( $tables as $table ) {
        if ( ! thia_table_exists( $table ) ) {
            thia_comment_moderator_install();
            break;
        }
    }
}

function thia_get_warning_count( $ip, $email ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_WARNINGS_TABLE;
    
    if ( ! thia_table_exists( $table ) ) {
        return 0;
    }
    
    $sql = "SELECT warning_count FROM " . $table . " WHERE ip = %s OR email = %s ORDER BY last_warning DESC LIMIT 1";
    
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
    $count = $wpdb->get_var( $wpdb->prepare( $sql, $ip, $email ) );
    
    return intval( $count );
}

/**
 * Increment warning count.
 */
function thia_increment_warning( $ip, $email ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_WARNINGS_TABLE;
    
    if ( ! thia_table_exists( $table ) ) {
        return 0;
    }
    
    $sql = "SELECT id, warning_count FROM " . $table . " WHERE ip = %s OR email = %s LIMIT 1";
    
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
    $existing = $wpdb->get_row( $wpdb->prepare( $sql, $ip, $email ) );
    
    if ( $existing ) {
        $new_count = $existing->warning_count + 1;
        $wpdb->update(
            $table,
            [
                'warning_count' => $new_count,
                'last_warning'  => current_time( 'mysql' )
            ],
            [ 'id' => $existing->id ],
            [ '%d', '%s' ],
            [ '%d' ]
        );
        return $new_count;
    } else {
        $wpdb->insert(
            $table,
            [
                'ip'            => $ip,
                'email'         => $email,
                'warning_count' => 1,
                'last_warning'  => current_time( 'mysql' )
            ]
        );
        return 1;
    }
}

/**
 * Clear warnings for IP/email.
 */
function thia_clear_warnings( $ip, $email ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_WARNINGS_TABLE;
    
    if ( ! thia_table_exists( $table ) ) {
        return;
    }
    
    if ( ! empty( $ip ) ) {
        $wpdb->delete( $table, [ 'ip' => $ip ], [ '%s' ] );
    }
    if ( ! empty( $email ) ) {
        $wpdb->delete( $table, [ 'email' => $email ], [ '%s' ] );
    }
}

/**
 * Record API call statistics.
 */
function thia_record_api_call( $success = true, $tokens_used = 0 ) {
    global $wpdb;
    $stats_table = $wpdb->prefix . THIAIDE_STATSAPI_TABLE;
    
    if ( ! thia_table_exists( $stats_table ) ) {
        return;
    }
    
    $today = current_time( 'Y-m-d' );
    
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders -- Table name is hardcoded constant.
    $existing = $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM `$stats_table` WHERE date = %s",
        $today
    ));
    
    if ( $existing ) {
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQLPlaceholders -- Table name is hardcoded constant.
        $wpdb->query( $wpdb->prepare(
            "UPDATE `$stats_table` SET 
                api_calls = api_calls + 1,
                total_tokens = total_tokens + %d,
                successful_calls = successful_calls + %d,
                failed_calls = failed_calls + %d,
                updated = NOW()
            WHERE date = %s",
            $tokens_used,
            $success ? 1 : 0,
            $success ? 0 : 1,
            $today
        ));
    } else {
        $wpdb->insert(
            $stats_table,
            [
                'date'             => $today,
                'api_calls'        => 1,
                'total_tokens'     => $tokens_used,
                'successful_calls' => $success ? 1 : 0,
                'failed_calls'     => $success ? 0 : 1,
                'created'          => current_time( 'mysql' ),
                'updated'          => current_time( 'mysql' )
            ]
        );
    }
}

/**
 * Check if IP is blocked.
 *
 * @param string $ip The IP address to check.
 * @return bool True if the IP is blocked, false otherwise.
 */
function thia_is_ip_blocked( $ip ) {
    global $wpdb;

    if ( empty( $ip ) || ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
        return false;
    }

    $table_name = $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE;

    if ( ! thia_table_exists( $table_name ) ) {
        return false;
    }

    $sql = "SELECT COUNT(*) FROM " . $table_name . " WHERE ip = %s";

    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
    $exists = $wpdb->get_var( $wpdb->prepare( $sql, $ip ) );

    return (int) $exists > 0;
}



/**
 * Check if user email is blocked.
 */
function thia_is_user_blocked( $email ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE;
    
    if ( ! thia_table_exists( $table ) || empty( $email ) ) {
        return false;
    }
    
    $sql = "SELECT COUNT(*) FROM " . $table . " WHERE email = %s";
    
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
    $exists = $wpdb->get_var( $wpdb->prepare( $sql, $email ) );
    
    return $exists > 0;
}

/**
 * Block an IP address.
 */
function thia_block_ip( $ip ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE;

    if ( ! thia_table_exists( $table ) ) {
        return;
    }

    if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) {
        return;
    }

    $sql = "SELECT COUNT(*) FROM " . $table . " WHERE ip = %s";
    
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
    $exists = $wpdb->get_var( $wpdb->prepare( $sql, $ip ) );
    
    if ( $exists > 0 ) {
        return;
    }

    $wpdb->insert( $table, [ 'ip' => $ip ] );
}

/**
 * Unblock an IP address.
 */
function thia_unblock_ip( $ip ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE;
    
    if ( ! thia_table_exists( $table ) ) {
        return false;
    }
    
    return $wpdb->delete( $table, [ 'ip' => $ip ], [ '%s' ] );
}

/**
 * Block a user email.
 */
function thia_block_user( $email ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE;

    if ( ! thia_table_exists( $table ) || empty( $email ) ) {
        return;
    }

    if ( ! is_email( $email ) ) {
        return;
    }

    $sql = "SELECT COUNT(*) FROM " . $table . " WHERE email = %s";
    
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
    $exists = $wpdb->get_var( $wpdb->prepare( $sql, $email ) );
    
    if ( $exists > 0 ) {
        return;
    }

    $wpdb->insert( $table, [ 'email' => $email ] );
}

/**
 * Unblock a user email.
 */
function thia_unblock_user( $email ) {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE;
    
    if ( ! thia_table_exists( $table ) ) {
        return false;
    }
    
    return $wpdb->delete( $table, [ 'email' => $email ], [ '%s' ] );
}

/**
 * Get API key from database.
 */
function thia_get_api_key() {
    global $wpdb;
    $table = $wpdb->prefix . THIAIDE_TABLE_NAME;

    if ( ! thia_table_exists( $table ) ) {
        return '';
    }

    $sql = "SELECT api_key FROM " . $table . " LIMIT 1";
    
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
    $key = $wpdb->get_var( $sql );
    
    return $key ? trim( $key ) : '';
}

/**
 * Validate API key with Thia Aide service.
 */
function thia_validate_api_key( $api_key ) {
    if ( empty( $api_key ) ) {
        return false;
    }
    
    $response = wp_remote_post(
        THIAIDE_API_URL,
        [
            'headers' => [ 'Content-Type' => 'application/json' ],
            'body'    => json_encode( [
                'api_key' => $api_key,
                'prompt'  => 'Respond with "OK" if this API key is valid.'
            ] ),
            'timeout' => 15,
        ]
    );
    
    if ( is_wp_error( $response ) ) {
        return false;
    }
    
    $body = json_decode( wp_remote_retrieve_body( $response ), true );
    
    return empty( $body['error'] );
}

/**
 * Build moderation prompt for AI.
 */
function thia_build_moderation_prompt( $content, $author, $ip ) {
    $prompt = "You are a comment moderator. Classify the comment.

RULES:
- safe = Any comment, including emotional, sarcastic, ironic, or critical opinions
- spam = Advertising, selling, links to products
- offensive = ONLY actual swear words and vulgar profanity
- hate = ONLY explicit racism, calls for genocide, extreme discrimination
- threat = ONLY explicit violence, physical harm, doxxing

IMPORTANT: 
1. CHECK THE ENTIRE TEXT - beginning, middle, and end
2. Do not ignore swear words, threats, hate speech, or spam even if surrounded by normal text
3. One single violation determines the classification

LANGUAGE INSTRUCTION:
- Write REASON and SUGGESTION in the same language as the comment!

Respond in EXACT format with MAX 10 words per line:
CLASSIFICATION: [safe/spam/offensive/hate/threat]
REASON: [1 short sentence]
SUGGESTION: [1 short sentence]

Comment:
\"\"\"{$content}\"\"\"";

    return $prompt;
}

/**
 * Check comment with AI moderation.
 *
 * @param int|string $approved    Comment approval status.
 * @param array      $comment_data Comment data.
 * @return int|string Modified approval status.
 */
function thia_comment_moderator_check( $approved, $comment_data ) {
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- This is a filter hook, not form processing.
    $is_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['action'] ) && $_POST['action'] === 'thia_moderate_comment';
    
    if ( isset( $comment_data['comment_approved'] ) && $comment_data['comment_approved'] === 'spam' ) {
        return $approved;
    }

    $content = $comment_data['comment_content'] ?? '';
    
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- $_SERVER['REMOTE_ADDR'] is safe, validated with filter_var.
    $ip_raw = isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
    $ip     = filter_var( $ip_raw, FILTER_VALIDATE_IP ) ? $ip_raw : '';
    
    $email  = $comment_data['comment_author_email'] ?? '';
    $author = $comment_data['comment_author'] ?? 'Anonymous';

    if ( thia_is_ip_blocked( $ip ) ) {
        return 'spam';
    }

    if ( thia_is_user_blocked( $email ) ) {
        return 'spam';
    }

    if ( empty( trim( $content ) ) ) {
        return 'spam';
    }
    
    if ( strlen( $content ) > 5000 ) {
        $content = substr( $content, 0, 5000 );
    }

    $api_key = thia_get_api_key();
    if ( empty( $api_key ) ) {
        return $approved;
    }

    $prompt = thia_build_moderation_prompt( $content, $author, $ip );

    $response = wp_remote_post(
        THIAIDE_API_URL,
        [
            'headers' => [ 'Content-Type' => 'application/json' ],
            'body'    => json_encode( [
                'api_key' => $api_key,
                'prompt'  => $prompt
            ] ),
            'timeout' => 60,
        ]
    );

    if ( is_wp_error( $response ) ) {
        return $approved;
    }

    $body = json_decode( wp_remote_retrieve_body( $response ), true );
    
    if ( isset( $body['error'] ) ) {
        return $approved;
    }
    
    $ai_response = $body['response'] ?? '';
    
    // Parse classification.
    $classification = 'safe';
    if ( preg_match( '/CLASSIFICATION:\s*(safe|spam|offensive|hate|threat)/i', $ai_response, $matches ) ) {
        $classification = strtolower( $matches[1] );
    } else {
        $classification = strtolower( trim( $ai_response ) );
        $classification = preg_replace( '/[^a-z]/', '', $classification );
    }
    
    $valid_categories = [ 'safe', 'spam', 'offensive', 'hate', 'threat' ];
    
    // Record API call.
    if ( isset( $body['tokens_used'] ) ) {
        thia_record_api_call( ! isset( $body['error'] ), $body['tokens_used'] );
    } else {
        thia_record_api_call( ! isset( $body['error'] ), strlen( $prompt ) / 4 );
    }
    
    if ( ! in_array( $classification, $valid_categories, true ) ) {
        return $approved;
    }

    if ( $is_ajax ) {
        return $classification === 'safe' ? 1 : $classification;
    }

    if ( in_array( $classification, [ 'spam', 'offensive', 'hate', 'threat' ], true ) ) {
        if ( isset( $comment_data['comment_ID'] ) ) {
            wp_trash_comment( $comment_data['comment_ID'] );
        }
        
        thia_block_ip( $ip );
        
        if ( ! empty( $email ) && is_email( $email ) ) {
            thia_block_user( $email );
        }
        
        return 'spam';
    }

    return 1;
}

/**
 * Rate limit check for AJAX requests.
 */
function thia_check_rate_limit( $ip, $action = 'moderate' ) {
    $rate_limit_key = 'thia_rate_limit_' . $action . '_' . $ip;
    $attempts       = get_transient( $rate_limit_key );
    
    if ( $attempts > 10 ) {
        return false;
    }
    
    if ( ! $attempts ) {
        set_transient( $rate_limit_key, 1, 60 );
    } else {
        set_transient( $rate_limit_key, $attempts + 1, 60 );
    }
    
    return true;
}

/**
 * AJAX: Moderate comment.
 */
add_action( 'wp_ajax_thia_moderate_comment', 'thia_ajax_moderate_comment' );
add_action( 'wp_ajax_nopriv_thia_moderate_comment', 'thia_ajax_moderate_comment' );
function thia_ajax_moderate_comment() {
    // Verify nonce.
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_verify_nonce() handles sanitization.
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'thia_moderate_comment' ) ) {
    wp_send_json_error( __( 'Security check failed.', 'thia-aide-comment-moderator' ) );
}
    
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- $_SERVER['REMOTE_ADDR'] is safe, validated with filter_var.
    $ip_raw = isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
    $ip     = filter_var( $ip_raw, FILTER_VALIDATE_IP ) ? $ip_raw : '';
    
    // Rate limit check.
    if ( ! thia_check_rate_limit( $ip, 'moderate' ) ) {
        wp_send_json_error( __( 'Too many requests. Please slow down.', 'thia-aide-comment-moderator' ) );
    }
    
    // Get and sanitize comment data.
    $comment_content  = isset( $_POST['comment_content'] ) ? sanitize_textarea_field( wp_unslash( $_POST['comment_content'] ) ) : '';
    $comment_post_ID  = isset( $_POST['comment_post_ID'] ) ? intval( $_POST['comment_post_ID'] ) : 0;
    
    // Get user info.
    if ( is_user_logged_in() ) {
        $current_user   = wp_get_current_user();
        $comment_author = $current_user->display_name;
        $comment_email  = $current_user->user_email;
        $comment_url    = $current_user->user_url;
    } else {
        $comment_author = isset( $_POST['comment_author'] ) ? sanitize_text_field( wp_unslash( $_POST['comment_author'] ) ) : '';
        $comment_email  = isset( $_POST['comment_email'] ) ? sanitize_email( wp_unslash( $_POST['comment_email'] ) ) : '';
        $comment_url    = isset( $_POST['comment_url'] ) ? esc_url_raw( wp_unslash( $_POST['comment_url'] ) ) : '';
    }
    
    // Validate.
    if ( empty( $comment_content ) ) {
        wp_send_json_error( __( 'Comment content is required.', 'thia-aide-comment-moderator' ) );
    }
    
    // Check if already blocked.
    if ( thia_is_ip_blocked( $ip ) ) {
        wp_send_json_success( [
            'classification' => 'blocked',
            'message'        => __( 'Your IP has been blocked.', 'thia-aide-comment-moderator' ),
            'reason'         => __( 'Your IP address is in the blocked list.', 'thia-aide-comment-moderator' ),
            'suggestion'     => __( 'Contact the site administrator.', 'thia-aide-comment-moderator' )
        ] );
    }
    
    if ( ! empty( $comment_email ) && thia_is_user_blocked( $comment_email ) ) {
        wp_send_json_success( [
            'classification' => 'blocked',
            'message'        => __( 'Your email has been blocked.', 'thia-aide-comment-moderator' ),
            'reason'         => __( 'Your email address is in the blocked list.', 'thia-aide-comment-moderator' ),
            'suggestion'     => __( 'Contact the site administrator.', 'thia-aide-comment-moderator' )
        ] );
    }
    
    // Get API key.
    $api_key = thia_get_api_key();
    if ( empty( $api_key ) ) {
        wp_send_json_error( __( 'API key not configured.', 'thia-aide-comment-moderator' ) );
    }
    
    $prompt = thia_build_moderation_prompt( $comment_content, $comment_author, $ip );
    
    // Send to API.
    $response = wp_remote_post(
        THIAIDE_API_URL,
        [
            'headers' => [ 'Content-Type' => 'application/json' ],
            'body'    => json_encode( [
                'api_key'     => $api_key,
                'temperature' => 0.1,
                'prompt'      => $prompt
            ] ),
            'timeout' => 60,
        ]
    );
    
    if ( is_wp_error( $response ) ) {
        wp_send_json_error( __( 'API communication error.', 'thia-aide-comment-moderator' ) );
    }
    
    $response_body = wp_remote_retrieve_body( $response );
    $body          = json_decode( $response_body, true );
    $ai_response   = $body['response'] ?? '';
    
    // Parse AI response.
    $classification = 'safe';
    $reason         = '';
    $suggestion     = '';
    
    if ( preg_match( '/CLASSIFICATION:\s*(safe|spam|offensive|hate|threat)/i', $ai_response, $matches ) ) {
        $classification = strtolower( $matches[1] );
    } else {
        $classification = strtolower( trim( $ai_response ) );
        $classification = preg_replace( '/[^a-z]/', '', $classification );
    }
    
    if ( preg_match( '/REASON:\s*(.+?)(?=SUGGESTION:|$)/is', $ai_response, $matches ) ) {
        $reason = trim( $matches[1] );
    }
    
    if ( preg_match( '/SUGGESTION:\s*(.+?)$/is', $ai_response, $matches ) ) {
        $suggestion = trim( $matches[1] );
    }
    
    // Record API call.
    if ( isset( $body['tokens_used'] ) ) {
        thia_record_api_call( ! isset( $body['error'] ), $body['tokens_used'] );
    } else {
        thia_record_api_call( ! isset( $body['error'] ), strlen( $prompt ) / 4 );
    }
    
    // Handle based on classification.
    if ( $classification === 'spam' || $classification === 'threat' ) {
        thia_block_ip( $ip );
        if ( ! empty( $comment_email ) && is_email( $comment_email ) ) {
            thia_block_user( $comment_email );
        }
        
        /* translators: %s = classification type (spam, threat) */
        $default_reason = sprintf( __( 'This comment was identified as %s.', 'thia-aide-comment-moderator' ), $classification );
        
        wp_send_json_success( [
            'classification' => 'blocked',
            'message'        => __( 'Comment blocked.', 'thia-aide-comment-moderator' ),
            'reason'         => $reason ?: $default_reason,
            'suggestion'     => $suggestion ?: __( 'Please post appropriate content.', 'thia-aide-comment-moderator' )
        ] );
    }
    
    if ( $classification === 'offensive' || $classification === 'hate' ) {
        $warning_count = thia_get_warning_count( $ip, $comment_email );
        
        if ( $warning_count >= 2 ) {
            thia_block_ip( $ip );
            if ( ! empty( $comment_email ) && is_email( $comment_email ) ) {
                thia_block_user( $comment_email );
            }
            thia_clear_warnings( $ip, $comment_email );
            
            wp_send_json_success( [
                'classification' => 'blocked',
                'message'        => __( 'You have been blocked due to repeated violations.', 'thia-aide-comment-moderator' ),
                'reason'         => $reason ?: __( 'Multiple warnings ignored.', 'thia-aide-comment-moderator' ),
                'suggestion'     => __( 'Your IP and email have been blocked. Contact the administrator if this was a mistake.', 'thia-aide-comment-moderator' )
            ] );
        } else {
            $new_count     = thia_increment_warning( $ip, $comment_email );
            $attempts_left = 3 - $new_count;
            
            /* translators: %d = current warning count (1, 2, or 3) */
            $warning_message = sprintf( __( 'Warning %d/3', 'thia-aide-comment-moderator' ), $new_count );
            
            /* translators: %d = number of remaining attempts before block */
            $warning_suggestion = sprintf( __( 'Please review your comment. You have %d attempt(s) left before being blocked.', 'thia-aide-comment-moderator' ), $attempts_left );
            
            wp_send_json_success( [
                'classification' => 'warning',
                'message'        => $warning_message,
                'reason'         => $reason ?: __( 'This comment may be inappropriate.', 'thia-aide-comment-moderator' ),
                'suggestion'     => $suggestion ?: $warning_suggestion
            ] );
        }
    }
    
    if ( $classification === 'safe' ) {
        thia_clear_warnings( $ip, $comment_email );
        
        wp_send_json_success( [
            'classification' => 'safe',
            'message'        => __( 'Comment approved.', 'thia-aide-comment-moderator' ),
            'reason'         => '',
            'suggestion'     => ''
        ] );
    }
    
    wp_send_json_error( __( 'Unknown classification.', 'thia-aide-comment-moderator' ) );
}

/**
 * AJAX: Save approved comment.
 */
add_action( 'wp_ajax_thia_save_comment', 'thia_ajax_save_comment' );
add_action( 'wp_ajax_nopriv_thia_save_comment', 'thia_ajax_save_comment' );
function thia_ajax_save_comment() {
    // Verify nonce.
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_verify_nonce() handles sanitization.
   if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'thia_save_comment' ) ) {
    wp_send_json_error( __( 'Security check failed.', 'thia-aide-comment-moderator' ) );
}
    
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- $_SERVER['REMOTE_ADDR'] is safe, validated with filter_var.
    $ip_raw = isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
    $ip     = filter_var( $ip_raw, FILTER_VALIDATE_IP ) ? $ip_raw : '';
    
    // Rate limit check.
    if ( ! thia_check_rate_limit( $ip, 'save' ) ) {
        wp_send_json_error( __( 'Too many requests. Please slow down.', 'thia-aide-comment-moderator' ) );
    }
    
    // Get user info.
    if ( is_user_logged_in() ) {
        $current_user   = wp_get_current_user();
        $comment_author = $current_user->display_name;
        $comment_email  = $current_user->user_email;
        $comment_url    = $current_user->user_url;
    } else {
        $comment_author = isset( $_POST['comment_author'] ) ? sanitize_text_field( wp_unslash( $_POST['comment_author'] ) ) : '';
        $comment_email  = isset( $_POST['comment_email'] ) ? sanitize_email( wp_unslash( $_POST['comment_email'] ) ) : '';
        $comment_url    = isset( $_POST['comment_url'] ) ? esc_url_raw( wp_unslash( $_POST['comment_url'] ) ) : '';
    }
    
    $comment_data = [
        'comment_post_ID'      => isset( $_POST['comment_post_ID'] ) ? intval( $_POST['comment_post_ID'] ) : 0,
        'comment_author'       => $comment_author,
        'comment_author_email' => $comment_email,
        'comment_author_url'   => $comment_url,
        'comment_content'      => isset( $_POST['comment_content'] ) ? sanitize_textarea_field( wp_unslash( $_POST['comment_content'] ) ) : '',
        'comment_approved'     => 1,
    ];
    
    $comment_id = wp_insert_comment( $comment_data );
    
    if ( $comment_id ) {
        wp_send_json_success( [
            'comment_id' => $comment_id,
            'message'    => __( 'Comment saved successfully.', 'thia-aide-comment-moderator' )
        ] );
    } else {
        wp_send_json_error( __( 'Failed to save comment.', 'thia-aide-comment-moderator' ) );
    }
}

/**
 * AJAX: Search blocked IPs/emails.
 */
add_action( 'wp_ajax_thia_search_blocked', 'thia_ajax_search_blocked' );
function thia_ajax_search_blocked() {
    // Check permissions.
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( __( 'Unauthorized.', 'thia-aide-comment-moderator' ), 403 );
    }
    
    // Verify nonce.
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_verify_nonce() handles sanitization.
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'thia_admin_action' ) ) {
    wp_send_json_error( __( 'Security check failed.', 'thia-aide-comment-moderator' ) );
}
    
    $search = isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '';
    $type   = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
    
    global $wpdb;
    
    if ( $type === 'ip' ) {
        $table = $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE;
        $sql   = "SELECT ip, blocked_at FROM " . $table . " WHERE ip LIKE %s ORDER BY blocked_at DESC LIMIT 50";
        
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
        $results = $wpdb->get_results( $wpdb->prepare( $sql, '%' . $wpdb->esc_like( $search ) . '%' ) );
        
        $data = [];
        foreach ( $results as $row ) {
            $data[] = [
                'value' => $row->ip,
                'date'  => $row->blocked_at
            ];
        }
        wp_send_json_success( $data );
    }
    
    if ( $type === 'email' ) {
        $table = $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE;
        $sql   = "SELECT email, blocked_at FROM " . $table . " WHERE email LIKE %s ORDER BY blocked_at DESC LIMIT 50";
        
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is constructed safely from hardcoded table name.
        $results = $wpdb->get_results( $wpdb->prepare( $sql, '%' . $wpdb->esc_like( $search ) . '%' ) );
        
        $data = [];
        foreach ( $results as $row ) {
            $data[] = [
                'value' => $row->email,
                'date'  => $row->blocked_at
            ];
        }
        wp_send_json_success( $data );
    }
    
    wp_send_json_error( __( 'Invalid type.', 'thia-aide-comment-moderator' ) );
}

/**
 * AJAX: Unblock IP.
 */
add_action( 'wp_ajax_thia_unblock_ip', 'thia_ajax_unblock_ip' );
function thia_ajax_unblock_ip() {
    // Check permissions.
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( __( 'Unauthorized.', 'thia-aide-comment-moderator' ), 403 );
    }
    
    // Verify nonce.
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_verify_nonce() handles sanitization.
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'thia_admin_action' ) ) {
    wp_send_json_error( __( 'Security check failed.', 'thia-aide-comment-moderator' ) );
}
    
    $ip     = isset( $_POST['ip'] ) ? sanitize_text_field( wp_unslash( $_POST['ip'] ) ) : '';
    $result = thia_unblock_ip( $ip );
    
    if ( $result ) {
        wp_send_json_success( [ 'message' => __( 'IP unblocked successfully.', 'thia-aide-comment-moderator' ) ] );
    } else {
        wp_send_json_error( __( 'Failed to unblock IP.', 'thia-aide-comment-moderator' ) );
    }
}

/**
 * AJAX: Unblock user.
 */
add_action( 'wp_ajax_thia_unblock_user', 'thia_ajax_unblock_user' );
function thia_ajax_unblock_user() {
    // Check permissions.
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( __( 'Unauthorized.', 'thia-aide-comment-moderator' ), 403 );
    }
    
    // Verify nonce.
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- wp_verify_nonce() handles sanitization.
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'thia_admin_action' ) ) {
        wp_send_json_error( __( 'Security check failed.', 'thia-aide-comment-moderator' ) );
    }
    
    $email  = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
    $result = thia_unblock_user( $email );
    
    if ( $result ) {
        wp_send_json_success( [ 'message' => __( 'User unblocked successfully.', 'thia-aide-comment-moderator' ) ] );
    } else {
        wp_send_json_error( __( 'Failed to unblock user.', 'thia-aide-comment-moderator' ) );
    }
}

/**
 * Enqueue frontend scripts and styles.
 */
add_action( 'wp_enqueue_scripts', 'thia_enqueue_scripts' );
function thia_enqueue_scripts() {
    if ( is_singular() && comments_open() ) {
        wp_enqueue_script(
            'thia-moderation',
            THIAIDE_PLUGIN_URL . 'assets/js/thia-moderation.js',
            [ 'jquery' ],
            THIAIDE_VERSION,
            true
        );
        
        wp_localize_script(
            'thia-moderation',
            'thia_ajax',
            [
                'ajax_url'       => admin_url( 'admin-ajax.php' ),
                'moderate_nonce' => wp_create_nonce( 'thia_moderate_comment' ),
                'save_nonce'     => wp_create_nonce( 'thia_save_comment' ),
                'messages'       => [
                    'checking' => __( 'Thia is reviewing your comment...', 'thia-aide-comment-moderator' ),
                    'approved' => __( 'Comment approved! Publishing...', 'thia-aide-comment-moderator' ),
                    'blocked'  => __( 'Comment blocked!', 'thia-aide-comment-moderator' ),
                    'warning'  => __( 'Please review your comment', 'thia-aide-comment-moderator' ),
                    'error'    => __( 'Error processing comment. Please try again.', 'thia-aide-comment-moderator' )
                ]
            ]
        );
        
        wp_enqueue_style(
            'thia-moderation',
            THIAIDE_PLUGIN_URL . 'assets/css/thia-moderation.css',
            [],
            THIAIDE_VERSION
        );
    }
}

/**
 * Enqueue admin scripts and styles.
 */
add_action( 'admin_enqueue_scripts', 'thia_enqueue_admin_scripts' );
function thia_enqueue_admin_scripts( $hook ) {
    if ( strpos( $hook, 'thia-moderator' ) !== false || $hook === 'toplevel_page_thia-moderator' ) {
        wp_enqueue_style(
            'thia-admin',
            THIAIDE_PLUGIN_URL . 'assets/css/thia-admin.css',
            [],
            THIAIDE_VERSION
        );
        
        wp_enqueue_script(
            'thia-admin',
            THIAIDE_PLUGIN_URL . 'assets/js/thia-admin.js',
            [ 'jquery' ],
            THIAIDE_VERSION,
            true
        );
        
        wp_localize_script(
            'thia-admin',
            'thia_admin',
            [
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce'    => wp_create_nonce( 'thia_admin_action' ),
                'messages' => [
                    'confirm_unblock_ip'    => __( 'Are you sure you want to unblock this IP?', 'thia-aide-comment-moderator' ),
                    'confirm_unblock_email' => __( 'Are you sure you want to unblock this user?', 'thia-aide-comment-moderator' )
                ]
            ]
        );
    }
}

/**
 * Add header before comment form.
 */
add_action( 'comment_form_before', 'thia_add_comments_header' );
function thia_add_comments_header() {
    if ( is_singular() && comments_open() ) {
        $icon_url = THIAIDE_PLUGIN_URL . 'img/thia_avatar.png';
        ?>
        <div class="thia-comments-header">
            <div class="thia-comments-header-icon">
                <img src="<?php echo esc_url( $icon_url ); ?>" alt="<?php esc_attr_e( 'Thia Aide AI Moderator', 'thia-aide-comment-moderator' ); ?>">
            </div>
            <div class="thia-comments-header-text">
                <strong><?php esc_html_e( 'Thia Aide AI Comment Moderator', 'thia-aide-comment-moderator' ); ?></strong> - 
                <?php esc_html_e( 'Your comment will be reviewed by Thia before publication. Spam and threats are blocked immediately.', 'thia-aide-comment-moderator' ); ?>
            </div>
        </div>
        <?php
    }
}

/**
 * Add admin menu.
 */
function thia_comment_moderator_add_admin_menu() {
    $icon_url = THIAIDE_PLUGIN_URL . 'img/thia_avatar.png';
    
    add_menu_page(
        __( 'Thia Moderator', 'thia-aide-comment-moderator' ),
        __( 'Thia Moderator', 'thia-aide-comment-moderator' ),
        'manage_options',
        'thia-moderator',
        'thia_comment_moderator_admin_page',
        $icon_url,
        65
    );
}

/**
 * Admin page callback.
 */
function thia_comment_moderator_admin_page() {
    $api_key = thia_get_api_key();
    $error   = '';
    $success = '';
    
// Handle API key save.
if ( isset( $_POST['submit'] ) && check_admin_referer( 'thia_save_api_key' ) ) {
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- Validated via isset() check below.
    $new_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : '';
    
    if ( empty( $new_key ) ) {
        $error = __( 'Please enter the API key.', 'thia-aide-comment-moderator' );
    } else {
        global $wpdb;
        $table = $wpdb->prefix . THIAIDE_TABLE_NAME;
        
        if ( ! thia_table_exists( $table ) ) {
            $error = __( 'Table not created. Please deactivate and reactivate the plugin.', 'thia-aide-comment-moderator' );
        } else {
            if ( thia_validate_api_key( $new_key ) ) {
                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name is hardcoded constant.
                $wpdb->query( "DELETE FROM `$table`" );
                $wpdb->insert( $table, [ 'api_key' => $new_key ] );
                $success = __( 'API key saved successfully!', 'thia-aide-comment-moderator' );
                $api_key = $new_key;
            } else {
                $error = __( 'Invalid API key. Please check your key and try again.', 'thia-aide-comment-moderator' );
            }
        }
    }
}
    
    // Get statistics.
    global $wpdb;
    $stats_table        = $wpdb->prefix . THIAIDE_STATSAPI_TABLE;
    $today              = current_time( 'Y-m-d' );
    $first_day_of_month = gmdate( 'Y-m-01', strtotime( $today ) );
    
    $stats_today = [ 'calls' => 0, 'success_rate' => 0 ];
    $stats_month = [ 'calls' => 0 ];
    
    if ( thia_table_exists( $stats_table ) ) {
        $sql_today = "SELECT api_calls as calls, successful_calls FROM " . $stats_table . " WHERE date = %s";
        
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql_today is constructed safely from hardcoded table name.
        $today_data = $wpdb->get_row( $wpdb->prepare( $sql_today, $today ), ARRAY_A );
        
        if ( $today_data ) {
            $stats_today['calls'] = $today_data['calls'];
            $success_rate = $today_data['calls'] > 0 ? round( ( $today_data['successful_calls'] / $today_data['calls'] ) * 100 ) : 0;
            $stats_today['success_rate'] = $success_rate;
        }
        
        $sql_month = "SELECT SUM(api_calls) as calls FROM " . $stats_table . " WHERE date >= %s";
        
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql_month is constructed safely from hardcoded table name.
        $month_data = $wpdb->get_row( $wpdb->prepare( $sql_month, $first_day_of_month ), ARRAY_A );
        
        if ( $month_data ) {
            $stats_month['calls'] = $month_data['calls'] ?: 0;
        }
    }
    
    // Get blocked counts.
    $table_ips       = $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE;
    $table_users     = $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE;
    $table_warnings  = $wpdb->prefix . THIAIDE_WARNINGS_TABLE;
    
    $sql_ips = "SELECT COUNT(*) FROM " . $table_ips;
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql_ips is constructed safely from hardcoded table name.
    $blocked_ips = thia_table_exists( $table_ips ) ? $wpdb->get_var( $sql_ips ) : 0;
    
    $sql_users = "SELECT COUNT(*) FROM " . $table_users;
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql_users is constructed safely from hardcoded table name.
    $blocked_users = thia_table_exists( $table_users ) ? $wpdb->get_var( $sql_users ) : 0;
    
    $sql_warnings = "SELECT SUM(warning_count) FROM " . $table_warnings;
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql_warnings is constructed safely from hardcoded table name.
    $active_warnings = thia_table_exists( $table_warnings ) ? $wpdb->get_var( $sql_warnings ) : 0;
    
    $header_bg = THIAIDE_PLUGIN_URL . 'img/thiastat.png';
    $logo_url  = THIAIDE_PLUGIN_URL . 'img/thaide-support.png';
    ?>
        <?php if ( wp_is_mobile() ) : ?>
        <div class="mobile-thiaide-container">
<div class="mobile-thiaide-header-section" style="background-image: url('<?php echo esc_url($header_bg); ?>')">
<div class="mobile-thiaide-header-content">
        <?php else : ?>
        <div class="thiaide-container">
<div class="thiaide-header-section" style="background-image: url('<?php echo esc_url($header_bg); ?>')">
<div class="thiaide-header-content">
        <?php endif; ?>
<div style="display: flex; align-items: center;">
                    <img src="<?php echo esc_url($logo_url); ?>" 
                         alt="Thia Aide AI Assistant" 
                         border="0" 
                         width="300" 
                         style="margin-right: 15px;">
                </div>
             <?php if ( wp_is_mobile() ) { ?>
            <div class="mobile-thiaide-stats-container">
            <?php } else { ?>
            <div class="thiaide-stats-container">
            <?php } ?>
                <div class="thiaide-stat-item">
                    <div class="thiaide-stat-value" style="color: #007cba;"><?php echo esc_html( $stats_today['calls'] ); ?></div>
                    <div class="thiaide-stat-label">Today</div>
                    <?php if ($stats_today['calls'] == 0): ?>
                    <div class="thiaide-stat-ready">Ready</div>
                    <?php endif; ?>
                </div>
                
                <div class="thiaide-divider"></div>
                
                <div class="thiaide-stat-item">
                    <div class="thiaide-stat-value" style="color: #6f42c1;"><?php echo esc_html( $stats_month['calls'] ); ?></div>
                    <div class="thiaide-stat-label">Month</div>
                    <?php 
                    $today = current_time('Y-m-d');
                    $first_day_of_month = date('Y-m-01', strtotime($today));
                    if ($first_day_of_month == $today && $stats_month['calls'] == 0):
                    ?>
                    <div class="thiaide-stat-ready">New month</div>
                    <?php endif; ?>
                </div>
                
                <div class="thiaide-divider"></div>
                
                <div class="thiaide-stat-item">
                    <div class="thiaide-stat-value" style="color: <?php echo $stats_today['success_rate'] >= 90 ? '#28a745' : ($stats_today['success_rate'] >= 70 ? '#ffc107' : '#dc3545'); ?>;">
                        <?php echo esc_html( $stats_today['success_rate'] ); ?>%
                    </div>
                    <div class="thiaide-stat-label">Success</div>
                </div>
            </div>
                    </div>
                </div>
    <div class="thia-wrap">
        
        
        <?php if ($success): ?>
            <div class="notice notice-success is-dismissible"><p><?php echo esc_html($success); ?></p></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="notice notice-error is-dismissible"><p><?php echo esc_html($error); ?></p></div>
        <?php endif; ?>

<div class="thia-apistat-form">
<div class="thia-api-moderator-form"> 
        <form method="post">
            <?php wp_nonce_field('thia_save_api_key'); ?>
            <table class="form-table">
                 <tr>
                    <th><label for="api_key">API Key</label></th>
                    <td>
                        <input type="password" name="api_key" id="api_key" class="regular-text" value="<?php echo esc_attr($api_key); ?>" />
                        <p class="description">Enter your API key from <a href="https://www.thiaide.com/product/thia-aide-ai-comment-moderator-wordpress-plugin/" target="_blank">Thiaide</a> service.</p>
                      </td>
                  </tr>
              </table>

            <?php submit_button('Save API Key', 'primary'); ?>
        </form>
</div>
<div class="thia-statistics">
    <h3>Moderation Statistics</h3>
    <div class="thia-stats-grid">
        <div class="thia-stat-card">
            <div class="thia-stat-icon"><svg width="45" height="45" viewBox="0 0 45 45" fill="none">
    <circle cx="22.5" cy="22.5" r="20" stroke="white" stroke-width="2" fill="none"/>
    <path d="M14 14 L31 31" stroke="white" stroke-width="2" stroke-linecap="round"/>
    <path d="M31 14 L14 31" stroke="white" stroke-width="2" stroke-linecap="round"/>
</svg></div>
            <div class="thia-stat-info">
                <span class="thia-stat-number"><?php
                    global $wpdb;
                    $table_ips = $wpdb->prefix . THIAIDE_BLOCKED_IPS_TABLE;
                    $blocked_ips = thia_table_exists($table_ips) ? $wpdb->get_var("SELECT COUNT(*) FROM `$table_ips`") : 0;
                    echo esc_html($blocked_ips);
                ?></span>
                <span class="thia-stat-label">Blocked IPs</span>
            </div>
        </div>
        
        <div class="thia-stat-card">
            <div class="thia-stat-icon"><svg width="45" height="45" viewBox="0 0 45 45" fill="none">
    <circle cx="22.5" cy="15" r="7" stroke="white" stroke-width="2" fill="none"/>
    <path d="M5 38 L5 35 C5 28 12 23 22.5 23 C33 23 40 28 40 35 L40 38" stroke="white" stroke-width="2" fill="none" stroke-linecap="round"/>
</svg></div>
            <div class="thia-stat-info">
                <span class="thia-stat-number"><?php
                    $table_users = $wpdb->prefix . THIAIDE_BLOCKED_USERS_TABLE;
                    $blocked_users = thia_table_exists($table_users) ? $wpdb->get_var("SELECT COUNT(*) FROM `$table_users`") : 0;
                    echo esc_html($blocked_users);
                ?></span>
                <span class="thia-stat-label">Blocked Users</span>
            </div>
        </div>
        
        <div class="thia-stat-card">
            <div class="thia-stat-icon"><svg width="45" height="45" viewBox="0 0 45 45" fill="none">
    <path d="M22.5 5 L42 38 L3 38 L22.5 5Z" stroke="white" stroke-width="2" fill="none"/>
    <rect x="21" y="24" width="3" height="10" fill="white"/>
    <circle cx="22.5" cy="36" r="1.5" fill="white"/>
</svg></div>
            <div class="thia-stat-info">
                <span class="thia-stat-number"><?php
                    $table_warnings = $wpdb->prefix . THIAIDE_WARNINGS_TABLE;
                    $active_warnings = thia_table_exists($table_warnings) ? $wpdb->get_var("SELECT SUM(warning_count) FROM `$table_warnings`") : 0;
                    echo esc_html($active_warnings ?: 0);
                ?></span>
                <span class="thia-stat-label">Active Warnings</span>
            </div>
        </div>
    </div>
</div>
</div>
<div class="thia-search-form">
    <h2>Search Blocked IPs & Users</h2>
    
    <div class="thia-search-tabs">
        <button class="thia-tab-btn active" data-tab="ip">IP Addresses</button>
        <button class="thia-tab-btn" data-tab="email">Email Addresses</button>
    </div>
    
    <div class="thia-search-box">
        <input type="text" id="thia-search-input" placeholder="Search by IP or email..." class="regular-text">
        <button id="thia-search-btn" class="button">Search</button>
    </div>
    
    <div id="thia-search-results">
        <div class="thia-search-message">Enter search term to find blocked IPs or emails</div>
    </div>
</div>
</div>
    <div class="thiaide-footer">
            &copy; <?php echo date('Y'); ?> Thia Aide All rights reserved.
        </div>
    </div>
    <?php
}