<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/templates/comments.php
// Description: Unified comment inbox -- view, reply, and manage comments across Facebook, Instagram, X, WordPress, and WooCommerce - NUCLEAR+++
// Last Edited: 2026-05-15
// ==================================================

defined('ABSPATH') || exit;

$current_plan = (string) get_option('automarketer_ai_plan_id', 'free');
$is_gated     = ($current_plan === 'free');

$wp_comments_enabled = (bool) get_option('amai_wp_comments_enabled', false);
$woo_active          = class_exists('WooCommerce');

// Build the active channel list dynamically.
$channels = ['facebook', 'instagram', 'x'];
if ($wp_comments_enabled) {
    $channels[] = 'wordpress';
    if ($woo_active) {
        $channels[] = 'woocommerce';
    }
}

$allowed_channel_filters = array_merge(['all'], $channels);
$channel_filter = sanitize_key((string) ($_GET['channel'] ?? 'all'));
if (!in_array($channel_filter, $allowed_channel_filters, true)) {
    $channel_filter = 'all';
}
$status_filter = sanitize_key((string) ($_GET['status'] ?? 'all'));
if (!in_array($status_filter, ['all', 'new', 'pending_review', 'replied', 'ignored'], true)) {
    $status_filter = 'all';
}

$base_url = admin_url('admin.php?page=automarketer-ai-comments');

global $wpdb;
$table = $wpdb->prefix . 'amai_social_comments';

// Settings for reply modes and tones.
$reply_modes    = [];
$reply_tones    = [];
$default_tones  = [
    'facebook'    => 'friendly',
    'instagram'   => 'warm',
    'x'           => 'professional',
    'wordpress'   => 'friendly',
    'woocommerce' => 'friendly',
];
$available_tones = ['friendly', 'warm', 'professional', 'playful', 'formal'];

foreach ($channels as $ch) {
    $reply_modes[$ch] = (string) get_option('amai_comment_reply_mode_' . $ch, 'manual');
    $reply_tones[$ch] = (string) get_option('amai_comment_reply_tone_' . $ch, $default_tones[$ch]);
}

// Unread counts per channel.
$unread_counts = [];
foreach ($channels as $ch) {
    $unread_counts[$ch] = (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM `{$table}` WHERE channel = %s AND status IN ('new','pending_review')",
            $ch
        )
    );
}
$total_unread = array_sum($unread_counts);

// Fetch comments for the inbox.
$where_parts = [];
$where_args  = [];

if ($channel_filter !== 'all') {
    $where_parts[] = 'channel = %s';
    $where_args[]  = $channel_filter;
}
if ($status_filter !== 'all') {
    $where_parts[] = 'status = %s';
    $where_args[]  = $status_filter;
}

$where_sql = $where_parts ? 'WHERE ' . implode(' AND ', $where_parts) : '';

$per_page   = 30;
$current_pg = max(1, (int) ($_GET['paged'] ?? 1));
$offset     = ($current_pg - 1) * $per_page;

if ($where_args) {
    $total_rows = (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM `{$table}` {$where_sql}",
            ...$where_args
        )
    );
    $comments = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM `{$table}` {$where_sql} ORDER BY commented_at DESC LIMIT %d OFFSET %d",
            ...array_merge($where_args, [$per_page, $offset])
        ),
        ARRAY_A
    );
} else {
    $total_rows = (int) $wpdb->get_var("SELECT COUNT(*) FROM `{$table}`");
    $comments   = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM `{$table}` ORDER BY commented_at DESC LIMIT %d OFFSET %d",
            $per_page,
            $offset
        ),
        ARRAY_A
    );
}

if (!is_array($comments)) {
    $comments = [];
}

$total_pages = $total_rows > 0 ? (int) ceil($total_rows / $per_page) : 1;

// Channel display labels and colors.
$channel_labels = [
    'facebook'    => 'Facebook',
    'instagram'   => 'Instagram',
    'x'           => 'X',
    'wordpress'   => 'WordPress',
    'woocommerce' => 'WooCommerce',
];
$channel_colors = [
    'facebook'    => '#1877F2',
    'instagram'   => '#E1306C',
    'x'           => '#000000',
    'wordpress'   => '#3858E9',
    'woocommerce' => '#7F54B3',
];

// Status display labels.
$status_labels = [
    'new'            => 'New',
    'pending_review' => 'Pending Review',
    'replied'        => 'Replied',
    'ignored'        => 'Ignored',
];
?>
<div class="wrap amai-comments-wrap">

    <div class="amai-comments-header">
        <div class="amai-comments-header-left">
            <h1 class="amai-comments-title">Comment Inbox</h1>
            <p class="amai-comments-subtitle">Manage and reply to comments across your channels in one place.</p>
        </div>
        <div class="amai-comments-header-right">
            <button class="amai-comments-settings-btn" id="amai-open-reply-settings" type="button">
                Reply Settings
            </button>
        </div>
    </div>

    <?php if ($is_gated) : ?>
    <div class="amai-comments-gate-notice">
        <div class="amai-comments-gate-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" fill="#D97757"/>
            </svg>
        </div>
        <div>
            <strong>Comment Inbox is available on Starter and above.</strong>
            Upgrade your plan to start managing and replying to comments directly from AutoMarketer AI.
        </div>
        <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-billing')); ?>" class="amai-comments-upgrade-btn">
            View Plans
        </a>
    </div>
    <?php endif; ?>

    <div class="amai-comments-channel-bar">
        <a href="<?php echo esc_url($base_url); ?>"
           class="amai-comments-channel-pill<?php echo $channel_filter === 'all' ? ' active' : ''; ?>">
            All
            <?php if ($total_unread > 0) : ?>
            <span class="amai-comments-badge"><?php echo esc_html((string) $total_unread); ?></span>
            <?php endif; ?>
        </a>
        <?php foreach ($channels as $ch) : ?>
        <a href="<?php echo esc_url(add_query_arg('channel', $ch, $base_url)); ?>"
           class="amai-comments-channel-pill<?php echo $channel_filter === $ch ? ' active' : ''; ?>">
            <?php echo esc_html($channel_labels[$ch]); ?>
            <?php if ($unread_counts[$ch] > 0) : ?>
            <span class="amai-comments-badge"><?php echo esc_html((string) $unread_counts[$ch]); ?></span>
            <?php endif; ?>
        </a>
        <?php endforeach; ?>
    </div>

    <div class="amai-comments-status-bar">
        <?php
        $status_options = [
            'all'            => 'All',
            'new'            => 'New',
            'pending_review' => 'Pending Review',
            'replied'        => 'Replied',
            'ignored'        => 'Ignored',
        ];
        foreach ($status_options as $sv => $sl) :
            $href = add_query_arg(['status' => $sv, 'channel' => $channel_filter], $base_url);
        ?>
        <a href="<?php echo esc_url($href); ?>"
           class="amai-comments-status-tab<?php echo $status_filter === $sv ? ' active' : ''; ?>">
            <?php echo esc_html($sl); ?>
        </a>
        <?php endforeach; ?>
    </div>

    <div class="amai-comments-inbox" id="amai-comments-inbox">
        <?php if (empty($comments)) : ?>
        <div class="amai-comments-empty">
            <p>No comments found<?php echo $channel_filter !== 'all' ? ' for ' . esc_html($channel_labels[$channel_filter] ?? $channel_filter) : ''; ?><?php echo $status_filter !== 'all' ? ' with status "' . esc_html($status_labels[$status_filter] ?? $status_filter) . '"' : ''; ?>.</p>
        </div>
        <?php else : ?>
        <?php foreach ($comments as $row) :
            $row_id       = (int) $row['id'];
            $row_channel  = (string) $row['channel'];
            $row_status   = (string) $row['status'];
            $row_author   = (string) $row['author_name'];
            $row_content  = (string) $row['content'];
            $row_ai_draft = (string) ($row['ai_draft'] ?? '');
            $row_reply    = (string) ($row['reply_content'] ?? '');
            $row_time     = (string) $row['commented_at'];
            $row_followup = (bool) $row['is_followup'];
            $mode         = $reply_modes[$row_channel] ?? 'manual';
            $is_unread    = in_array($row_status, ['new', 'pending_review'], true);
        ?>
        <div class="amai-comment-row<?php echo $is_unread ? ' unread' : ''; ?><?php echo $row_followup ? ' followup' : ''; ?>"
             data-id="<?php echo esc_attr((string) $row_id); ?>"
             data-channel="<?php echo esc_attr($row_channel); ?>"
             data-status="<?php echo esc_attr($row_status); ?>">

            <div class="amai-comment-row-left">
                <div class="amai-comment-channel-dot" style="background:<?php echo esc_attr($channel_colors[$row_channel] ?? '#999'); ?>"></div>
                <?php if ($is_unread) : ?><div class="amai-comment-unread-dot"></div><?php endif; ?>
            </div>

            <div class="amai-comment-row-body">
                <div class="amai-comment-row-meta">
                    <span class="amai-comment-author"><?php echo esc_html($row_author ?: 'Unknown'); ?></span>
                    <span class="amai-comment-channel-label"><?php echo esc_html($channel_labels[$row_channel] ?? $row_channel); ?></span>
                    <?php if ($row_followup) : ?>
                    <span class="amai-comment-followup-pill">Followup</span>
                    <?php endif; ?>
                    <span class="amai-comment-time"><?php echo esc_html(human_time_diff(strtotime($row_time), time()) . ' ago'); ?></span>
                </div>
                <div class="amai-comment-content"><?php echo esc_html($row_content); ?></div>

                <?php if ($row_status === 'replied' && $row_reply !== '') : ?>
                <div class="amai-comment-sent-reply">
                    <span class="amai-comment-sent-label">Your reply:</span>
                    <?php echo esc_html($row_reply); ?>
                </div>
                <?php endif; ?>

                <?php if ($row_status === 'pending_review' && $row_ai_draft !== '') : ?>
                <div class="amai-comment-draft-block" id="draft-block-<?php echo esc_attr((string) $row_id); ?>">
                    <div class="amai-comment-draft-label">AI draft ready for review:</div>
                    <textarea class="amai-comment-reply-textarea"
                              id="reply-text-<?php echo esc_attr((string) $row_id); ?>"
                              rows="3"><?php echo esc_textarea($row_ai_draft); ?></textarea>
                    <div class="amai-comment-draft-actions">
                        <button type="button"
                                class="amai-comment-send-btn"
                                data-id="<?php echo esc_attr((string) $row_id); ?>">
                            Send Reply
                        </button>
                        <button type="button"
                                class="amai-comment-ignore-btn"
                                data-id="<?php echo esc_attr((string) $row_id); ?>">
                            Ignore
                        </button>
                    </div>
                </div>
                <?php endif; ?>

                <?php if ($row_status === 'new') : ?>
                <div class="amai-comment-actions" id="actions-<?php echo esc_attr((string) $row_id); ?>">
                    <button type="button"
                            class="amai-comment-reply-toggle"
                            data-id="<?php echo esc_attr((string) $row_id); ?>">
                        Reply
                    </button>
                    <?php if ($mode === 'manual') : ?>
                    <button type="button"
                            class="amai-comment-ai-draft-btn"
                            data-id="<?php echo esc_attr((string) $row_id); ?>">
                        Generate AI Draft
                    </button>
                    <?php endif; ?>
                    <button type="button"
                            class="amai-comment-ignore-btn"
                            data-id="<?php echo esc_attr((string) $row_id); ?>">
                        Ignore
                    </button>
                    <div class="amai-comment-manual-reply-block" id="manual-reply-<?php echo esc_attr((string) $row_id); ?>" style="display:none;">
                        <textarea class="amai-comment-reply-textarea"
                                  id="reply-text-<?php echo esc_attr((string) $row_id); ?>"
                                  rows="3"
                                  placeholder="Write your reply..."></textarea>
                        <div class="amai-comment-draft-actions">
                            <button type="button"
                                    class="amai-comment-send-btn"
                                    data-id="<?php echo esc_attr((string) $row_id); ?>">
                                Send Reply
                            </button>
                            <button type="button"
                                    class="amai-comment-cancel-reply"
                                    data-id="<?php echo esc_attr((string) $row_id); ?>">
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <div class="amai-comment-row-right">
                <span class="amai-comment-status-pill amai-comment-status-pill--<?php echo esc_attr($row_status); ?>">
                    <?php echo esc_html($status_labels[$row_status] ?? $row_status); ?>
                </span>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if ($total_pages > 1) : ?>
        <div class="amai-comments-pagination">
            <?php if ($current_pg > 1) : ?>
            <a href="<?php echo esc_url(add_query_arg(['paged' => $current_pg - 1, 'channel' => $channel_filter, 'status' => $status_filter], $base_url)); ?>"
               class="amai-comments-page-btn">Previous</a>
            <?php endif; ?>
            <span class="amai-comments-page-info">Page <?php echo esc_html((string) $current_pg); ?> of <?php echo esc_html((string) $total_pages); ?></span>
            <?php if ($current_pg < $total_pages) : ?>
            <a href="<?php echo esc_url(add_query_arg(['paged' => $current_pg + 1, 'channel' => $channel_filter, 'status' => $status_filter], $base_url)); ?>"
               class="amai-comments-page-btn">Next</a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<div class="amai-comments-settings-modal" id="amai-reply-settings-modal" style="display:none;">
    <div class="amai-comments-settings-backdrop" id="amai-reply-settings-backdrop"></div>
    <div class="amai-comments-settings-panel">
        <div class="amai-comments-settings-header">
            <h2 class="amai-comments-settings-title">Reply Settings</h2>
            <button type="button" class="amai-comments-settings-close" id="amai-close-reply-settings">
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M14 4L4 14M4 4L14 14" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
                </svg>
            </button>
        </div>
        <div class="amai-comments-settings-body">
            <?php foreach ($channels as $ch) : ?>
            <div class="amai-channel-settings-block">
                <div class="amai-channel-settings-name">
                    <span class="amai-channel-dot" style="background:<?php echo esc_attr($channel_colors[$ch]); ?>"></span>
                    <?php echo esc_html($channel_labels[$ch]); ?>
                </div>

                <div class="amai-settings-field">
                    <label class="amai-settings-label" for="reply-mode-<?php echo esc_attr($ch); ?>">Reply mode</label>
                    <select class="amai-settings-select amai-reply-mode-select"
                            id="reply-mode-<?php echo esc_attr($ch); ?>"
                            data-channel="<?php echo esc_attr($ch); ?>">
                        <option value="manual"<?php selected($reply_modes[$ch], 'manual'); ?>>Manual -- I reply myself</option>
                        <option value="ai_assisted"<?php selected($reply_modes[$ch], 'ai_assisted'); ?>>AI-assisted -- draft ready for my review</option>
                        <option value="autopilot"<?php selected($reply_modes[$ch], 'autopilot'); ?>>Autopilot -- AI replies automatically</option>
                    </select>
                </div>

                <div class="amai-settings-field">
                    <label class="amai-settings-label" for="reply-tone-<?php echo esc_attr($ch); ?>">Tone</label>
                    <select class="amai-settings-select amai-reply-tone-select"
                            id="reply-tone-<?php echo esc_attr($ch); ?>"
                            data-channel="<?php echo esc_attr($ch); ?>"
                            data-default="<?php echo esc_attr($default_tones[$ch]); ?>">
                        <?php foreach ($available_tones as $tone) : ?>
                        <option value="<?php echo esc_attr($tone); ?>"<?php selected($reply_tones[$ch], $tone); ?>>
                            <?php echo esc_html(ucfirst($tone)); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="amai-settings-hint" id="tone-hint-<?php echo esc_attr($ch); ?>"
                       style="<?php echo $reply_tones[$ch] !== $default_tones[$ch] ? '' : 'display:none;'; ?>">
                        The default tone for <?php echo esc_html($channel_labels[$ch]); ?> is
                        <strong><?php echo esc_html(ucfirst($default_tones[$ch])); ?></strong> -- change only if you have a specific reason.
                    </p>
                </div>
            </div>
            <?php endforeach; ?>

            <?php if (!$wp_comments_enabled) : ?>
            <div class="amai-comments-wp-enable-notice">
                <p>Want to manage WordPress comments and WooCommerce reviews here too?</p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-settings')); ?>">
                    Enable in Settings
                </a>
            </div>
            <?php endif; ?>
        </div>
        <div class="amai-comments-settings-footer">
            <button type="button" class="amai-comments-save-settings-btn" id="amai-save-reply-settings">
                Save Settings
            </button>
            <button type="button" class="amai-comments-settings-cancel" id="amai-cancel-reply-settings">
                Cancel
            </button>
        </div>
    </div>
</div>