<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/templates/reputation.php
// Description: Reputation hub -- tabbed view for Social Comments and Review Responder - NUCLEAR+++
// Last Edited: 2026-05-17
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

$active_modules      = (array) get_option('amai_active_modules', []);
$cm_active           = in_array('comment-manager', $active_modules, true);
$rr_active           = in_array('review-responder', $active_modules, true);
$current_plan        = (string) get_option('automarketer_ai_plan_id', 'free');
$google_connected    = GoogleAuth::isConnected();

$tab = sanitize_key((string) ($_GET['tab'] ?? ''));
if ($tab === '') {
    $tab = $cm_active ? 'comments' : 'reviews';
}
if (!in_array($tab, ['comments', 'reviews'], true)) {
    $tab = 'comments';
}

$base_url = admin_url('admin.php?page=automarketer-ai-reputation');
?>
<div class="amai-reputation-wrap">

    <!-- ══════════════════════════════════════════════════════
         PAGE HEADER
    ══════════════════════════════════════════════════════ -->
    <div class="amai-rep-header">
        <h1>Reputation</h1>
        <p>Manage every comment and review from one place. AI drafts responses, you stay in control.</p>
        <?php include AMAI_PLUGIN_DIR . 'templates/partials/tabs.php'; ?>
    </div>

    <!-- ══════════════════════════════════════════════════════
         REPUTATION TABS
    ══════════════════════════════════════════════════════ -->
    <div class="amai-rep-tabs">
        <?php if ($cm_active): ?>
            <a href="<?php echo esc_url($base_url . '&tab=comments'); ?>"
               class="amai-rep-tab<?php echo $tab === 'comments' ? ' amai-rep-tab--active' : ''; ?>">
                Social Comments
                <?php
                global $wpdb;
                $unread_comments = (int) $wpdb->get_var(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}amai_social_comments WHERE status IN ('new', 'pending_review')"
                );
                if ($unread_comments > 0):
                ?>
                    <span class="amai-rep-badge"><?php echo esc_html((string) $unread_comments); ?></span>
                <?php endif; ?>
            </a>
        <?php endif; ?>
        <?php if ($rr_active): ?>
            <a href="<?php echo esc_url($base_url . '&tab=reviews'); ?>"
               class="amai-rep-tab<?php echo $tab === 'reviews' ? ' amai-rep-tab--active' : ''; ?>">
                Reviews
                <?php
                $unread_reviews = (int) $wpdb->get_var(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}amai_reviews WHERE status IN ('new', 'pending_review')"
                );
                if ($unread_reviews > 0):
                ?>
                    <span class="amai-rep-badge"><?php echo esc_html((string) $unread_reviews); ?></span>
                <?php endif; ?>
            </a>
        <?php endif; ?>
    </div>

    <!-- ══════════════════════════════════════════════════════
         TAB CONTENT
    ══════════════════════════════════════════════════════ -->
    <?php if ($tab === 'comments'): ?>

        <?php if (!$cm_active): ?>
            <div class="amai-rep-gate">
                <p>Comment Manager is not active. Activate it from the Modules page to manage social comments.</p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>" class="amai-rep-gate-btn">Go to Modules</a>
            </div>
        <?php else: ?>
            <?php include AMAI_PLUGIN_DIR . 'templates/comments.php'; ?>
        <?php endif; ?>

    <?php elseif ($tab === 'reviews'): ?>

        <?php if (!$rr_active): ?>
            <div class="amai-rep-gate">
                <p>Review Responder is not active. Activate it from the Modules page to manage reviews.</p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>" class="amai-rep-gate-btn">Go to Modules</a>
            </div>
        <?php else: ?>
            <?php
            // ── Reply mode and tone settings ────────────────────
            $reply_mode = (string) get_option('amai_review_reply_mode', 'ai_assisted');
            $reply_tone = (string) get_option('amai_review_reply_tone', 'professional');

            // ── Filters ─────────────────────────────────────────
            $status_filter   = sanitize_key((string) ($_GET['rstatus'] ?? 'needs_action'));
            $platform_filter = sanitize_key((string) ($_GET['rplatform'] ?? 'all'));
            $star_filter     = isset($_GET['rstar']) ? (int) $_GET['rstar'] : 0;

            if (!in_array($status_filter, ['needs_action', 'all', 'new', 'pending_review', 'replied', 'ignored'], true)) {
                $status_filter = 'needs_action';
            }

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

            // ── Build query ──────────────────────────────────────
            $where  = ['1=1'];
            $params = [];

            if ($status_filter === 'needs_action') {
                $where[] = "status IN ('new', 'pending_review')";
            } elseif ($status_filter !== 'all') {
                $where[]  = 'status = %s';
                $params[] = $status_filter;
            }

            if ($platform_filter !== 'all' && $platform_filter !== '') {
                $where[]  = 'platform = %s';
                $params[] = $platform_filter;
            }

            if ($star_filter >= 1 && $star_filter <= 5) {
                $where[]  = 'star_rating = %d';
                $params[] = $star_filter;
            }

            $where_sql = implode(' AND ', $where);
            $query     = "SELECT * FROM {$table} WHERE {$where_sql} ORDER BY review_date DESC LIMIT 50";
            $reviews   = !empty($params)
                ? $wpdb->get_results($wpdb->prepare($query, ...$params), ARRAY_A)
                : $wpdb->get_results($query, ARRAY_A);

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

            // ── Platform list for filter ─────────────────────────
            $platforms = $wpdb->get_col("SELECT DISTINCT platform FROM {$table} ORDER BY platform ASC");
            if (!is_array($platforms)) {
                $platforms = [];
            }

            $review_base_url = $base_url . '&tab=reviews';
            ?>

            <!-- Settings bar -->
            <div class="amai-rev-settings-bar">
                <div class="amai-rev-mode-wrap">
                    <span class="amai-rev-mode-label">Reply mode:</span>
                    <select id="amai-rev-mode" class="amai-rev-select">
                        <option value="manual"      <?php selected($reply_mode, 'manual'); ?>>Manual</option>
                        <option value="ai_assisted" <?php selected($reply_mode, 'ai_assisted'); ?>>AI Assisted</option>
                        <option value="autopilot"   <?php selected($reply_mode, 'autopilot'); ?>>Autopilot</option>
                    </select>
                    <span class="amai-rev-mode-label">Tone:</span>
                    <select id="amai-rev-tone" class="amai-rev-select">
                        <option value="professional" <?php selected($reply_tone, 'professional'); ?>>Professional</option>
                        <option value="warm"         <?php selected($reply_tone, 'warm'); ?>>Warm</option>
                        <option value="friendly"     <?php selected($reply_tone, 'friendly'); ?>>Friendly</option>
                    </select>
                    <button id="amai-rev-save-settings" class="amai-rev-btn-save">Save</button>
                    <span id="amai-rev-settings-msg" class="amai-rev-settings-msg"></span>
                </div>

                <?php if (!$google_connected): ?>
                    <div class="amai-rev-notice amai-rev-notice--warn">
                        Google Business Profile is not connected. Connect it on the
                        <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=google')); ?>">Social Media</a> page to start fetching reviews.
                    </div>
                <?php endif; ?>
            </div>

            <!-- Filters -->
            <div class="amai-rev-filters">
                <?php
                $status_opts = [
                    'needs_action'   => 'Needs Action',
                    'all'            => 'All',
                    'replied'        => 'Replied',
                    'ignored'        => 'Ignored',
                ];
                foreach ($status_opts as $val => $label):
                    $active_class = $status_filter === $val ? ' amai-rev-filter--active' : '';
                    $href = esc_url(add_query_arg(['rstatus' => $val, 'rplatform' => $platform_filter, 'rstar' => $star_filter ?: null], $review_base_url));
                ?>
                    <a href="<?php echo $href; ?>" class="amai-rev-filter<?php echo $active_class; ?>"><?php echo esc_html($label); ?></a>
                <?php endforeach; ?>

                <?php if (count($platforms) > 1): ?>
                    <span class="amai-rev-filter-sep">|</span>
                    <?php foreach ($platforms as $p):
                        $active_class = $platform_filter === $p ? ' amai-rev-filter--active' : '';
                        $href = esc_url(add_query_arg(['rstatus' => $status_filter, 'rplatform' => $p], $review_base_url));
                    ?>
                        <a href="<?php echo $href; ?>" class="amai-rev-filter<?php echo $active_class; ?>"><?php echo esc_html(ucfirst($p)); ?></a>
                    <?php endforeach; ?>
                <?php endif; ?>

                <!-- Star filter -->
                <span class="amai-rev-filter-sep">|</span>
                <?php for ($s = 1; $s <= 5; $s++):
                    $active_class = $star_filter === $s ? ' amai-rev-filter--active' : '';
                    $href = esc_url(add_query_arg(['rstatus' => $status_filter, 'rstar' => $s], $review_base_url));
                ?>
                    <a href="<?php echo $href; ?>" class="amai-rev-filter amai-rev-filter--star<?php echo $active_class; ?>">
                        <?php echo str_repeat('★', $s) . str_repeat('☆', 5 - $s); ?>
                    </a>
                <?php endfor; ?>
            </div>

            <!-- Review list -->
            <?php if (empty($reviews)): ?>
                <div class="amai-rev-empty">
                    <?php if ($status_filter === 'needs_action'): ?>
                        <p>You are all caught up. No reviews need a response right now.</p>
                    <?php else: ?>
                        <p>No reviews found. Once Google Business Profile reviews come in, they will appear here.</p>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="amai-rev-list">
                    <?php foreach ($reviews as $review):
                        $stars      = (int) $review['star_rating'];
                        $status     = (string) $review['status'];
                        $has_draft  = isset($review['ai_draft']) && $review['ai_draft'] !== '';
                        $has_reply  = isset($review['reply_text']) && $review['reply_text'] !== '';
                        $review_id  = (int) $review['id'];
                        $platform   = (string) $review['platform'];
                    ?>
                        <div class="amai-rev-row amai-rev-row--<?php echo esc_attr($status); ?>" data-review-id="<?php echo esc_attr((string) $review_id); ?>">

                            <div class="amai-rev-row-top">
                                <div class="amai-rev-meta">
                                    <span class="amai-rev-stars">
                                        <?php echo str_repeat('★', $stars) . str_repeat('☆', 5 - $stars); ?>
                                    </span>
                                    <span class="amai-rev-author"><?php echo esc_html($review['reviewer_name']); ?></span>
                                    <span class="amai-rev-platform amai-rev-platform--<?php echo esc_attr($platform); ?>"><?php echo esc_html(ucfirst($platform)); ?></span>
                                    <span class="amai-rev-date"><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($review['review_date']))); ?></span>
                                </div>
                                <div class="amai-rev-status amai-rev-status--<?php echo esc_attr($status); ?>">
                                    <?php
                                    $status_labels = [
                                        'new'            => 'New',
                                        'pending_review' => 'Draft ready',
                                        'replied'        => 'Replied',
                                        'ignored'        => 'Ignored',
                                    ];
                                    echo esc_html($status_labels[$status] ?? $status);
                                    ?>
                                </div>
                            </div>

                            <?php if (isset($review['comment']) && $review['comment'] !== ''): ?>
                                <div class="amai-rev-comment"><?php echo esc_html($review['comment']); ?></div>
                            <?php else: ?>
                                <div class="amai-rev-comment amai-rev-comment--no-text"><em>No written review - star rating only.</em></div>
                            <?php endif; ?>

                            <?php if ($status === 'replied' && $has_reply): ?>
                                <div class="amai-rev-reply-sent">
                                    <span class="amai-rev-reply-label">Your reply:</span>
                                    <?php echo esc_html($review['reply_text']); ?>
                                </div>
                            <?php elseif ($status !== 'ignored'): ?>
                                <div class="amai-rev-actions">
                                    <textarea class="amai-rev-textarea" rows="3" placeholder="Write a reply..."><?php echo esc_textarea($has_draft ? $review['ai_draft'] : ''); ?></textarea>
                                    <div class="amai-rev-btn-row">
                                        <?php if ($reply_mode !== 'manual' && !$has_draft): ?>
                                            <button class="amai-rev-btn amai-rev-btn--draft" data-review-id="<?php echo esc_attr((string) $review_id); ?>">
                                                Draft with AI
                                            </button>
                                        <?php endif; ?>
                                        <?php if ($platform === 'facebook'): ?>
                                            <button class="amai-rev-btn amai-rev-btn--copy" data-review-id="<?php echo esc_attr((string) $review_id); ?>">
                                                Copy &amp; Mark Replied
                                            </button>
                                        <?php else: ?>
                                            <button class="amai-rev-btn amai-rev-btn--post" data-review-id="<?php echo esc_attr((string) $review_id); ?>">
                                                Post Reply
                                            </button>
                                        <?php endif; ?>
                                        <button class="amai-rev-btn amai-rev-btn--ignore" data-review-id="<?php echo esc_attr((string) $review_id); ?>">
                                            Ignore
                                        </button>
                                    </div>
                                    <div class="amai-rev-row-msg"></div>
                                </div>
                            <?php endif; ?>

                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <script>
            (function() {
                const nonce   = <?php echo wp_json_encode(wp_create_nonce('amai_review_nonce')); ?>;
                const sNonce  = <?php echo wp_json_encode(wp_create_nonce('amai_review_settings_nonce')); ?>;
                const ajaxUrl = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;

                function post(action, data, cb) {
                    const body = new URLSearchParams(Object.assign({ action, _wpnonce: nonce }, data));
                    fetch(ajaxUrl, { method: 'POST', body })
                        .then(r => r.json())
                        .then(cb)
                        .catch(() => cb({ success: false, data: { message: 'Request failed.' } }));
                }

                document.addEventListener('click', function(e) {
                    const btn = e.target.closest('[class*="amai-rev-btn--"]');
                    if (!btn) return;
                    const row      = btn.closest('.amai-rev-row');
                    const reviewId = row ? row.dataset.reviewId : null;
                    const msgEl    = row ? row.querySelector('.amai-rev-row-msg') : null;
                    const textarea = row ? row.querySelector('.amai-rev-textarea') : null;

                    if (btn.classList.contains('amai-rev-btn--draft')) {
                        btn.disabled = true;
                        btn.textContent = 'Drafting...';
                        post('amai_review_generate_draft', { review_id: reviewId }, function(res) {
                            btn.disabled = false;
                            btn.textContent = 'Draft with AI';
                            if (res.success && textarea) {
                                textarea.value = res.data.draft;
                            } else if (msgEl) {
                                msgEl.textContent = res.data.message || 'Draft failed.';
                            }
                        });
                    }

                    if (btn.classList.contains('amai-rev-btn--post')) {
                        const replyText = textarea ? textarea.value.trim() : '';
                        if (!replyText) {
                            if (msgEl) msgEl.textContent = 'Please write or generate a reply first.';
                            return;
                        }
                        btn.disabled = true;
                        btn.textContent = 'Posting...';
                        post('amai_review_post_reply', { review_id: reviewId, reply_text: replyText }, function(res) {
                            btn.disabled = false;
                            btn.textContent = 'Post Reply';
                            if (res.success) {
                                row.classList.remove('amai-rev-row--new', 'amai-rev-row--pending_review');
                                row.classList.add('amai-rev-row--replied');
                                const actionsEl = row.querySelector('.amai-rev-actions');
                                if (actionsEl) {
                                    actionsEl.innerHTML = '<div class="amai-rev-reply-sent"><span class="amai-rev-reply-label">Your reply:</span> ' + replyText + '</div>';
                                }
                                const statusEl = row.querySelector('.amai-rev-status');
                                if (statusEl) statusEl.textContent = 'Replied';
                            } else if (msgEl) {
                                msgEl.textContent = res.data.message || 'Post failed.';
                            }
                        });
                    }

                    if (btn.classList.contains('amai-rev-btn--copy')) {
                        const replyText = textarea ? textarea.value.trim() : '';
                        if (!replyText) {
                            if (msgEl) msgEl.textContent = 'Please write or generate a reply first.';
                            return;
                        }
                        navigator.clipboard.writeText(replyText).catch(() => {});
                        post('amai_review_post_reply', { review_id: reviewId, reply_text: replyText }, function(res) {
                            if (res.success) {
                                row.classList.remove('amai-rev-row--new', 'amai-rev-row--pending_review');
                                row.classList.add('amai-rev-row--replied');
                                const actionsEl = row.querySelector('.amai-rev-actions');
                                if (actionsEl) {
                                    actionsEl.innerHTML = '<div class="amai-rev-reply-sent"><span class="amai-rev-reply-label">Your reply (copied):</span> ' + replyText + '<div class="amai-rev-fb-note">Paste this reply directly on your Facebook Page.</div></div>';
                                }
                                const statusEl = row.querySelector('.amai-rev-status');
                                if (statusEl) statusEl.textContent = 'Replied';
                            } else if (msgEl) {
                                msgEl.textContent = res.data.message || 'Save failed.';
                            }
                        });
                    }

                    if (btn.classList.contains('amai-rev-btn--ignore')) {
                        post('amai_review_ignore', { review_id: reviewId }, function(res) {
                            if (res.success) {
                                row.style.opacity = '0.4';
                                row.style.pointerEvents = 'none';
                                const statusEl = row.querySelector('.amai-rev-status');
                                if (statusEl) statusEl.textContent = 'Ignored';
                            }
                        });
                    }
                });

                // Settings save
                const saveBtn = document.getElementById('amai-rev-save-settings');
                if (saveBtn) {
                    saveBtn.addEventListener('click', function() {
                        const mode = document.getElementById('amai-rev-mode').value;
                        const tone = document.getElementById('amai-rev-tone').value;
                        const msg  = document.getElementById('amai-rev-settings-msg');
                        const body = new URLSearchParams({ action: 'amai_review_save_settings', _wpnonce: sNonce, reply_mode: mode, reply_tone: tone });
                        fetch(ajaxUrl, { method: 'POST', body })
                            .then(r => r.json())
                            .then(function(res) {
                                if (msg) msg.textContent = res.success ? 'Saved.' : (res.data.message || 'Save failed.');
                                setTimeout(() => { if (msg) msg.textContent = ''; }, 3000);
                            });
                    });
                }
            })();
            </script>

        <?php endif; // rr_active ?>

    <?php endif; // tab === reviews ?>

</div><!-- /.amai-reputation-wrap -->