<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-hot-thread-alerter.php
// Description: Detects posts receiving an unusual volume of comments in a short window and emails the site admin - NUCLEAR+++
// Last Edited: 2026-05-20
// ==================================================
namespace AutoMarketerAI;
defined('ABSPATH') || exit;

class HotThreadAlerter
{
    private const CRON_HOOK        = 'amai_hot_thread_check';
    private const INTERVAL         = 'amai_five_minutes';
    private const DEFAULT_THRESHOLD = 5;
    private const DEFAULT_WINDOW    = 2;
    private const COOLDOWN_HOURS    = 12;

    // --------------------------------------------------
    // Register cron hook. Reuses amai_five_minutes interval
    // already registered by BounceHandler -- no duplicate needed.
    // --------------------------------------------------
    public static function register(): void
    {
        add_action(self::CRON_HOOK, [self::class, 'run']);
        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time(), self::INTERVAL, self::CRON_HOOK);
        }
    }

    public static function deregister(): void
    {
        $timestamp = wp_next_scheduled(self::CRON_HOOK);
        if ($timestamp !== false) {
            wp_unschedule_event($timestamp, self::CRON_HOOK);
        }
    }

    // --------------------------------------------------
    // Cron entry point. Exits early if alerts are disabled.
    // --------------------------------------------------
    public static function run(): void
    {
        if (get_option('amai_hot_thread_alerts_enabled', '1') !== '1') {
            return;
        }

        $threshold = max(1, (int) get_option('amai_hot_thread_threshold', (string) self::DEFAULT_THRESHOLD));
        $window    = max(1, (int) get_option('amai_hot_thread_window', (string) self::DEFAULT_WINDOW));

        $hot = self::queryHotThreads($threshold, $window);
        foreach ($hot as $row) {
            $channel          = (string) $row->channel;
            $platform_post_id = (string) $row->platform_post_id;
            $count            = (int) $row->comment_count;

            if ($platform_post_id === '') {
                continue;
            }

            $cooldown_key = 'amai_ht_' . md5($channel . '_' . $platform_post_id);
            if (get_transient($cooldown_key) !== false) {
                continue;
            }

            self::sendAlert($channel, $platform_post_id, $count, $threshold, $window);
            set_transient($cooldown_key, '1', self::COOLDOWN_HOURS * HOUR_IN_SECONDS);
        }
    }

    // --------------------------------------------------
    // Query wp_amai_social_comments for posts exceeding
    // the comment threshold within the time window.
    // Returns only rows with a non-empty platform_post_id
    // so unmatched X mentions are excluded.
    // --------------------------------------------------
    private static function queryHotThreads(int $threshold, int $window): array
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_social_comments';
        $sql   = $wpdb->prepare(
            "SELECT channel, platform_post_id, COUNT(*) AS comment_count
               FROM `{$table}`
              WHERE created_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d HOUR)
                AND platform_post_id != ''
              GROUP BY channel, platform_post_id
             HAVING comment_count >= %d",
            $window,
            $threshold
        );
        $results = $wpdb->get_results($sql);
        return is_array($results) ? $results : [];
    }

    // --------------------------------------------------
    // Send alert email to site admin.
    // Uses add_filter/remove_all_filters pattern to send
    // HTML mail without permanently altering content type.
    // --------------------------------------------------
    private static function sendAlert(
        string $channel,
        string $platform_post_id,
        int    $count,
        int    $threshold,
        int    $window
    ): void {
        $admin_email = (string) get_option('admin_email', '');
        if ($admin_email === '') {
            return;
        }

        $site_name    = (string) get_bloginfo('name');
        $channel_label = ucfirst($channel);
        $subject      = $site_name . ': Hot thread alert - ' . $count . ' comments in ' . $window . ' hour' . ($window !== 1 ? 's' : '');

        ob_start();
        self::renderEmailBody($site_name, $channel_label, $platform_post_id, $count, $threshold, $window);
        $body = ob_get_clean();

        add_filter('wp_mail_content_type', static fn() => 'text/html');
        wp_mail($admin_email, $subject, (string) $body);
        remove_all_filters('wp_mail_content_type');
    }

    // --------------------------------------------------
    // Render the alert email HTML body.
    // Zero-marketing style: one useful fact, clear CTA.
    // --------------------------------------------------
    private static function renderEmailBody(
        string $site_name,
        string $channel_label,
        string $platform_post_id,
        int    $count,
        int    $threshold,
        int    $window
    ): void {
        $inbox_url     = admin_url('admin.php?page=automarketer-ai-reputation&tab=comments');
        $window_label  = $window . ' hour' . ($window !== 1 ? 's' : '');
        $comment_label = $count . ' comment' . ($count !== 1 ? 's' : '');
        ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hot thread alert</title>
</head>
<body style="margin:0;padding:0;background:#F9FAFB;font-family:'DM Sans',Arial,sans-serif;color:#1C1917;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;">
  <tr>
    <td align="center" style="padding:40px 16px;">
      <table width="560" cellpadding="0" cellspacing="0" style="background:#FFFFFF;border-radius:16px;border:1.5px solid #E7DDD5;overflow:hidden;">
        <tr>
          <td style="background:#D97757;height:6px;font-size:0;line-height:0;">&nbsp;</td>
        </tr>
        <tr>
          <td style="padding:32px 40px 8px;">
            <p style="margin:0 0 4px;font-size:12px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#D97757;">Hot thread</p>
            <h1 style="margin:0 0 8px;font-size:22px;font-weight:800;color:#1C1917;line-height:1.3;">
              <?php echo esc_html($comment_label); ?> in <?php echo esc_html($window_label); ?> on <?php echo esc_html($channel_label); ?>
            </h1>
            <p style="margin:0 0 24px;font-size:15px;color:#78716C;line-height:1.6;">
              One of your <?php echo esc_html(strtolower($channel_label)); ?> posts is picking up unusual comment activity. Now is a good time to jump in while the conversation is warm.
            </p>
            <table cellpadding="0" cellspacing="0" style="margin:0 0 24px;background:#FFF7F4;border-radius:10px;border:1.5px solid #F3D5C8;width:100%;">
              <tr>
                <td style="padding:16px 20px;">
                  <table cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                      <td style="font-size:13px;color:#78716C;padding-bottom:4px;">Channel</td>
                      <td align="right" style="font-size:13px;font-weight:600;color:#1C1917;"><?php echo esc_html($channel_label); ?></td>
                    </tr>
                    <tr>
                      <td style="font-size:13px;color:#78716C;padding-bottom:4px;">Comments in window</td>
                      <td align="right" style="font-size:13px;font-weight:600;color:#1C1917;"><?php echo esc_html((string) $count); ?></td>
                    </tr>
                    <tr>
                      <td style="font-size:13px;color:#78716C;padding-bottom:4px;">Window</td>
                      <td align="right" style="font-size:13px;font-weight:600;color:#1C1917;"><?php echo esc_html($window_label); ?></td>
                    </tr>
                    <tr>
                      <td style="font-size:13px;color:#78716C;">Post ID</td>
                      <td align="right" style="font-size:13px;font-weight:600;color:#1C1917;word-break:break-all;"><?php echo esc_html($platform_post_id); ?></td>
                    </tr>
                  </table>
                </td>
              </tr>
            </table>
            <table cellpadding="0" cellspacing="0">
              <tr>
                <td style="background:#D97757;border-radius:8px;">
                  <a href="<?php echo esc_url($inbox_url); ?>" style="display:inline-block;padding:12px 28px;font-size:14px;font-weight:700;color:#FFFFFF;text-decoration:none;">Open comment inbox</a>
                </td>
              </tr>
            </table>
          </td>
        </tr>
        <tr>
          <td style="padding:24px 40px 32px;border-top:1px solid #F5F5F4;margin-top:24px;">
            <p style="margin:0;font-size:12px;color:#A8A29E;line-height:1.6;">
              You are receiving this because hot thread alerts are enabled in <?php echo esc_html($site_name); ?> Settings. You can turn them off under Settings &gt; On-Post Comment Form.
            </p>
          </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</body>
</html>
        <?php
    }
}