<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-comment-digest.php
// Description: Sends a 15-minute email digest of unread social comments to the site admin - NUCLEAR+++
// Last Edited: 2026-05-15
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

class CommentDigest
{
    private const CRON_HOOK = 'amai_comment_digest';
    private const INTERVAL  = 'amai_fifteen_minutes';

    // --------------------------------------------------
    // Register cron schedule, hook, and schedule event.
    // --------------------------------------------------
    public static function register(): void
    {
        add_filter('cron_schedules', [self::class, 'addCronInterval']);
        add_action(self::CRON_HOOK, [self::class, 'send']);
        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time(), self::INTERVAL, self::CRON_HOOK);
        }
    }

    // --------------------------------------------------
    // Deregister on plugin deactivation.
    // --------------------------------------------------
    public static function deregister(): void
    {
        $timestamp = wp_next_scheduled(self::CRON_HOOK);
        if ($timestamp !== false) {
            wp_unschedule_event($timestamp, self::CRON_HOOK);
        }
    }

    // --------------------------------------------------
    // Register the 15-minute cron interval.
    // --------------------------------------------------
    public static function addCronInterval(array $schedules): array
    {
        $schedules[self::INTERVAL] = [
            'interval' => 900,
            'display'  => 'Every 15 minutes',
        ];
        return $schedules;
    }

    // --------------------------------------------------
    // Called by cron -- sends digest if there are unread
    // comments since the last digest was sent.
    // Tracks last send time in amai_comment_digest_last_sent.
    // --------------------------------------------------
    public static function send(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'amai_social_comments';

        $last_sent = (string) get_option('amai_comment_digest_last_sent', '');

        if ($last_sent !== '') {
            $rows = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM `{$table}`
                     WHERE status IN ('new','pending_review')
                     AND created_at > %s
                     ORDER BY commented_at DESC
                     LIMIT 50",
                    $last_sent
                ),
                ARRAY_A
            );
        } else {
            $rows = $wpdb->get_results(
                "SELECT * FROM `{$table}`
                 WHERE status IN ('new','pending_review')
                 ORDER BY commented_at DESC
                 LIMIT 50",
                ARRAY_A
            );
        }

        if (!is_array($rows) || count($rows) === 0) {
            return;
        }

        $admin_email = (string) get_option('admin_email', '');
        if ($admin_email === '') {
            return;
        }

        $site_name = (string) get_option('blogname', 'AutoMarketer AI');
        $count     = count($rows);
        $inbox_url = admin_url('admin.php?page=automarketer-ai-comments');

        $channel_labels = [
            'facebook'  => 'Facebook',
            'instagram' => 'Instagram',
            'x'         => 'X',
        ];

        $rows_html = '';
        foreach ($rows as $row) {
            $channel = $channel_labels[(string) ($row['channel'] ?? '')] ?? (string) ($row['channel'] ?? '');
            $author  = esc_html((string) ($row['author_name'] ?? 'Unknown'));
            $content = esc_html((string) ($row['content'] ?? ''));
            $status  = (string) ($row['status'] ?? 'new');
            $time    = esc_html((string) ($row['commented_at'] ?? ''));

            $status_label = $status === 'pending_review' ? 'Pending Review' : 'New';
            $status_color = $status === 'pending_review' ? '#92400E' : '#1E40AF';
            $status_bg    = $status === 'pending_review' ? '#FEF3C7' : '#DBEAFE';

            $rows_html .= '<tr style="border-bottom:1px solid #F5F0EC;">'
                . '<td style="padding:12px 16px;font-size:13px;color:#44403C;vertical-align:top;">'
                . '<strong style="color:#1C1917;">' . $author . '</strong>'
                . '<br><span style="font-size:11px;color:#78716C;">' . esc_html($channel) . ' &middot; ' . $time . '</span>'
                . '</td>'
                . '<td style="padding:12px 16px;font-size:13px;color:#44403C;vertical-align:top;">' . $content . '</td>'
                . '<td style="padding:12px 16px;vertical-align:top;white-space:nowrap;">'
                . '<span style="display:inline-block;padding:2px 8px;border-radius:99px;font-size:11px;font-weight:600;'
                . 'background:' . $status_bg . ';color:' . $status_color . ';">' . $status_label . '</span>'
                . '</td>'
                . '</tr>';
        }

        $plural  = $count !== 1;
        $subject = $site_name . ': ' . $count . ' unread comment' . ($plural ? 's' : '') . ' need' . ($plural ? '' : 's') . ' your attention';

        $body = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'
            . '<body style="margin:0;padding:0;background:#F9FAFB;font-family:Arial,sans-serif;">'
            . '<div style="max-width:600px;margin:32px auto;background:#fff;border-radius:12px;border:1.5px solid #E7DDD5;overflow:hidden;">'
            . '<div style="background:#D97757;padding:24px 28px;">'
            . '<div style="font-size:20px;font-weight:800;color:#fff;">' . esc_html($site_name) . '</div>'
            . '<div style="font-size:13px;color:rgba(255,255,255,0.85);margin-top:4px;">Comment Inbox Digest</div>'
            . '</div>'
            . '<div style="padding:24px 28px;">'
            . '<p style="font-size:15px;color:#1C1917;margin:0 0 16px;">'
            . 'You have <strong>' . $count . ' unread comment' . ($plural ? 's' : '') . '</strong> waiting for a reply.'
            . '</p>'
            . '<table style="width:100%;border-collapse:collapse;border:1.5px solid #E7DDD5;border-radius:8px;overflow:hidden;">'
            . '<thead><tr style="background:#F9FAFB;">'
            . '<th style="padding:10px 16px;text-align:left;font-size:11px;font-weight:600;color:#78716C;text-transform:uppercase;letter-spacing:0.04em;">Commenter</th>'
            . '<th style="padding:10px 16px;text-align:left;font-size:11px;font-weight:600;color:#78716C;text-transform:uppercase;letter-spacing:0.04em;">Comment</th>'
            . '<th style="padding:10px 16px;text-align:left;font-size:11px;font-weight:600;color:#78716C;text-transform:uppercase;letter-spacing:0.04em;">Status</th>'
            . '</tr></thead>'
            . '<tbody>' . $rows_html . '</tbody>'
            . '</table>'
            . '<div style="margin-top:24px;text-align:center;">'
            . '<a href="' . esc_url($inbox_url) . '" '
            . 'style="display:inline-block;background:#D97757;color:#fff;text-decoration:none;font-size:14px;font-weight:600;padding:12px 28px;border-radius:8px;">'
            . 'Open Comment Inbox</a>'
            . '</div>'
            . '<p style="font-size:12px;color:#A8A29E;margin-top:24px;text-align:center;">'
            . 'This digest is sent every 15 minutes when new unread comments are present.'
            . '</p>'
            . '</div>'
            . '</div>'
            . '</body></html>';

        $headers = ['Content-Type: text/html; charset=UTF-8'];
        wp_mail($admin_email, $subject, $body, $headers);
        update_option('amai_comment_digest_last_sent', gmdate('Y-m-d H:i:s'));
    }
}