<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /templates/results.php
// Description: Results proof dashboard -- is it working and is my phone ringing? - NUCLEAR+++
// Last Edited: 2026-05-19
// ==================================================
if (!defined('ABSPATH')) {
    exit;
}

global $wpdb;

// ── Business type detection ───────────────────────────────────────────
$business_type_override = get_option('amai_business_type_override', '');
$business_type_auto     = 'service';

$woo_active = class_exists('WooCommerce');
if ($woo_active) {
    $product_count = (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM {$wpdb->posts}
         WHERE post_type = 'product' AND post_status = 'publish'"
    );
    if ($product_count === 0) {
        $business_type_auto = 'saas';
    } else {
        $sub_plugin         = (
            class_exists('WC_Subscriptions') ||
            is_plugin_active('woocommerce-subscriptions/woocommerce-subscriptions.php')
        );
        $business_type_auto = $sub_plugin ? 'mixed' : 'product';
    }
}

if ($business_type_auto === 'service') {
    $gbp_conn = get_option('amai_gbp_connection', null);
    if (!empty($gbp_conn) && is_array($gbp_conn) && ($gbp_conn['status'] ?? '') === 'active') {
        $business_type_auto = 'local';
    }
}

$business_type = ($business_type_override !== '') ? $business_type_override : $business_type_auto;

// ── Section visibility matrix ─────────────────────────────────────────
$show_revenue_mrr    = in_array($business_type, ['saas', 'mixed'], true);
$show_revenue_orders = in_array($business_type, ['product', 'mixed'], true);
$show_store          = in_array($business_type, ['product', 'mixed'], true);
$show_revenue_card   = $show_revenue_mrr || $show_revenue_orders;

// ── Date ranges ───────────────────────────────────────────────────────
$now_utc      = gmdate('Y-m-d H:i:s');
$mtd_start    = gmdate('Y-m-') . '01 00:00:00';
$last30_start = gmdate('Y-m-d', strtotime('-29 days')) . ' 00:00:00';

// ── Stripe data (SaaS / Mixed) ────────────────────────────────────────
$sub_id       = get_option('automarketer_ai_stripe_sub_id', '');
$cust_id      = get_option('automarketer_ai_stripe_customer_id', '');
$has_stripe   = ($sub_id !== '' || $cust_id !== '');
$mrr_override = get_option('amai_mrr_override', null);
$license_status = get_option('automarketer_ai_license_status', 'inactive');
$subscriber_count = ($license_status === 'active' || $license_status === 'free') ? 1 : 0;

// ── WooCommerce order data (Product / Mixed) ──────────────────────────
$store_revenue   = null;
$store_orders    = null;
$store_connected = false;
if ($show_store && $woo_active) {
    $store_connected = true;
    $orders_result = $wpdb->get_row($wpdb->prepare(
        "SELECT COUNT(*) AS cnt, SUM(pm.meta_value) AS rev
         FROM {$wpdb->posts} p
         JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key = '_order_total'
         WHERE p.post_type = 'shop_order'
           AND p.post_status IN ('wc-completed','wc-processing')
           AND p.post_date >= %s",
        gmdate('Y-m-d', strtotime('-29 days'))
    ), ARRAY_A);
    if ($orders_result !== null) {
        $store_orders  = (int) ($orders_result['cnt'] ?? 0);
        $store_revenue = (float) ($orders_result['rev'] ?? 0.0);
    }
}

// ── GA4 data ──────────────────────────────────────────────────────────
$ga4_table     = $wpdb->prefix . 'amai_ga4_connection';
$ga4_connected = false;
$ga4_sessions  = 0;
$ga4_prev      = 0;
$ga4_top_posts = [];
$ga4_row       = null;

if ($wpdb->get_var("SHOW TABLES LIKE '{$ga4_table}'") === $ga4_table) {
    $ga4_row = $wpdb->get_row(
        "SELECT status, property_name FROM {$wpdb->prefix}amai_ga4_connection LIMIT 1",
        ARRAY_A
    );
    if ($ga4_row !== null && ($ga4_row['status'] ?? '') === 'active') {
        $ga4_connected = true;
        $metrics_table = $wpdb->prefix . 'amai_ga4_metrics';
        if ($wpdb->get_var("SHOW TABLES LIKE '{$metrics_table}'") === $metrics_table) {
            $ga4_sessions = (int) $wpdb->get_var(
                "SELECT SUM(sessions_30d) FROM {$metrics_table}"
            );
            $ga4_prev = (int) $wpdb->get_var(
                "SELECT SUM(sessions_prev_30d) FROM {$metrics_table}"
            );
            $ga4_top_posts = (array) $wpdb->get_results(
                "SELECT m.post_id, m.sessions_30d, p.post_title
                 FROM {$metrics_table} m
                 JOIN {$wpdb->posts} p ON p.ID = m.post_id
                 WHERE m.sessions_30d > 0 AND p.post_status = 'publish'
                 ORDER BY m.sessions_30d DESC
                 LIMIT 5",
                ARRAY_A
            );
        }
    }
}

$ga4_delta    = $ga4_prev > 0 ? round((($ga4_sessions - $ga4_prev) / $ga4_prev) * 100) : null;
$ga4_property = !empty($ga4_row['property_name']) ? (string) $ga4_row['property_name'] : '';

// ── Social data ───────────────────────────────────────────────────────
$posts_mtd = (int) $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'posted' AND scheduled_utc >= %s",
    $mtd_start
));

$channels_active = [];
if (\AutoMarketerAI\FacebookAuth::getConnection() !== null) {
    $channels_active[] = 'Facebook';
}
if (\AutoMarketerAI\FacebookAuth::getInstagramAccountId() !== null) {
    $channels_active[] = 'Instagram';
}
$x_conn = \AutoMarketerAI\XAuth::getConnection();
if ($x_conn !== null && ($x_conn['status'] ?? '') === 'active') {
    $channels_active[] = 'X';
}
$tk_conn = get_option('amai_tiktok_connection', null);
if (!empty($tk_conn) && is_array($tk_conn)) {
    $channels_active[] = 'TikTok';
}

$best_post = $wpdb->get_row($wpdb->prepare(
    "SELECT channel, post_content AS content, scheduled_utc,
            stat_likes, stat_comments, stat_reach,
            (COALESCE(stat_likes,0) + COALESCE(stat_comments,0)*3 + COALESCE(stat_reach,0)*0.01) AS score
     FROM {$wpdb->prefix}amai_scheduled_posts
     WHERE status = 'posted' AND scheduled_utc >= %s
       AND (stat_likes IS NOT NULL OR stat_comments IS NOT NULL OR stat_reach IS NOT NULL)
     ORDER BY score DESC
     LIMIT 1",
    $last30_start
), ARRAY_A);

// ── Reputation data ───────────────────────────────────────────────────
$reviews_table  = $wpdb->prefix . 'amai_reviews';
$reviews_exist  = ($wpdb->get_var("SHOW TABLES LIKE '{$reviews_table}'") === $reviews_table);
$review_count   = 0;
$avg_rating     = null;
$recent_reviews = [];

if ($reviews_exist) {
    $review_count = (int) $wpdb->get_var(
        "SELECT COUNT(*) FROM {$reviews_table} WHERE status != 'spam'"
    );
    $avg_rating = $wpdb->get_var(
        "SELECT ROUND(AVG(star_rating), 1) FROM {$reviews_table}
         WHERE star_rating > 0 AND status != 'spam'"
    );
    $recent_reviews = (array) $wpdb->get_results($wpdb->prepare(
        "SELECT reviewer_name, star_rating, comment, platform, review_date
         FROM {$reviews_table}
         WHERE status != 'spam' AND star_rating >= 4
         ORDER BY review_date DESC
         LIMIT 3"
    ), ARRAY_A);
}

// ── Blog content data ─────────────────────────────────────────────────
$blog_posts_30d = (int) $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->posts}
     WHERE post_type = 'post' AND post_status = 'publish'
       AND post_date >= %s",
    gmdate('Y-m-d', strtotime('-29 days'))
));

$blog_total = (int) $wpdb->get_var(
    "SELECT COUNT(*) FROM {$wpdb->posts}
     WHERE post_type = 'post' AND post_status = 'publish'"
);

// ── Helper: render star rating ────────────────────────────────────────
function amai_render_stars(float $rating): string
{
    $out = '<span class="amai-results-stars">';
    for ($i = 1; $i <= 5; $i++) {
        if ($rating >= $i) {
            $out .= '<span class="amai-star amai-star--full">&#9733;</span>';
        } elseif ($rating >= $i - 0.5) {
            $out .= '<span class="amai-star amai-star--half">&#9733;</span>';
        } else {
            $out .= '<span class="amai-star amai-star--empty">&#9734;</span>';
        }
    }
    $out .= '</span>';
    return $out;
}

// ── Localize JS ───────────────────────────────────────────────────────
wp_localize_script('amai-results', 'amaiResults', [
    'hasStripe'        => $has_stripe,
    'mrrOverride'      => $mrr_override,
    'subId'            => $sub_id,
    'custId'           => $cust_id,
    'ajaxUrl'          => admin_url('admin-ajax.php'),
    'nonce'            => wp_create_nonce('amai_dashboard_subscription'),
    'btNonce'          => wp_create_nonce('amai_set_business_type'),
    'businessType'     => $business_type,
    'businessTypeAuto' => $business_type_auto,
    'isOverride'       => ($business_type_override !== ''),
]);

$bt_labels = [
    'saas'    => 'SaaS',
    'service' => 'Service',
    'local'   => 'Local',
    'product' => 'Product',
    'mixed'   => 'Mixed',
];
?>

<div class="wrap amai-results-wrap" id="amai-root">

    <div class="amai-results-header">
        <h1 class="amai-results-title">Results</h1>
        <p class="amai-results-subtitle">Is your marketing working? Here's the proof.</p>
    </div>

    <div class="amai-results-bt-switcher">
        <span class="amai-results-bt-label">View as:</span>
        <div class="amai-results-bt-buttons" id="amai-bt-buttons">
            <?php foreach ($bt_labels as $key => $label): ?>
                <button
                    class="amai-results-bt-btn<?php echo $business_type === $key ? ' amai-results-bt-btn--active' : ''; ?>"
                    data-type="<?php echo esc_attr($key); ?>"
                ><?php echo esc_html($label); ?></button>
            <?php endforeach; ?>
        </div>
        <button
            class="amai-results-bt-reset<?php echo $business_type_override === '' ? ' amai-results-bt-reset--hidden' : ''; ?>"
            id="amai-bt-reset"
        >Auto-detect (<?php echo esc_html($bt_labels[$business_type_auto] ?? $business_type_auto); ?>)</button>
        <span class="amai-results-bt-saving" id="amai-bt-saving">Saving...</span>
    </div>

    <div class="amai-results-grid">

        <?php if ($show_revenue_card): ?>
        <!-- SECTION: Revenue -->
        <div class="amai-results-card amai-results-card--full amai-results-card--revenue">
            <div class="amai-results-card-header">
                <span class="amai-results-eyebrow">Revenue</span>
                <h2 class="amai-results-card-title">Your business in numbers</h2>
            </div>
            <div class="amai-results-stat-row">
                <?php if ($show_revenue_mrr): ?>
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number" id="amai-results-mrr">
                            <?php if ($mrr_override !== null): ?>
                                $<?php echo esc_html(number_format((float) $mrr_override, 2)); ?>
                            <?php elseif ($has_stripe): ?>
                                <span class="amai-results-loading">Loading...</span>
                            <?php else: ?>
                                $0.00
                            <?php endif; ?>
                        </div>
                        <div class="amai-results-stat-label">Monthly recurring revenue</div>
                        <div class="amai-results-stat-meta" id="amai-results-mrr-meta">
                            <?php if (!$has_stripe && $mrr_override === null): ?>
                                No active subscription
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="amai-results-stat-divider"></div>
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number" id="amai-results-subscribers">
                            <?php echo esc_html((string) $subscriber_count); ?>
                        </div>
                        <div class="amai-results-stat-label"><?php echo $subscriber_count === 1 ? 'Active subscriber' : 'Active subscribers'; ?></div>
                    </div>
                <?php endif; ?>
                <?php if ($show_revenue_orders): ?>
                    <?php if ($show_revenue_mrr): ?>
                        <div class="amai-results-stat-divider"></div>
                    <?php endif; ?>
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number">
                            <?php echo esc_html((string) ($store_orders ?? 0)); ?>
                        </div>
                        <div class="amai-results-stat-label">Orders last 30 days</div>
                    </div>
                    <?php if ($store_revenue !== null && $store_revenue > 0): ?>
                        <div class="amai-results-stat-divider"></div>
                        <div class="amai-results-stat">
                            <div class="amai-results-stat-number">
                                <?php echo esc_html(get_woocommerce_currency_symbol() . number_format($store_revenue, 2)); ?>
                            </div>
                            <div class="amai-results-stat-label">Revenue last 30 days</div>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- SECTION: Traffic -->
        <div class="amai-results-card amai-results-card--full">
            <div class="amai-results-card-header">
                <span class="amai-results-eyebrow">Traffic</span>
                <h2 class="amai-results-card-title">People are finding you</h2>
            </div>
            <?php if (!$ga4_connected): ?>
                <div class="amai-results-empty">
                    <p class="amai-results-empty-text">Connect Google Analytics to see how many people are visiting your site each month.</p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>" class="amai-results-cta">Connect GA4</a>
                </div>
            <?php elseif ($ga4_sessions === 0): ?>
                <div class="amai-results-empty">
                    <p class="amai-results-empty-text">Your site traffic will show up here once Google Analytics has had a chance to collect some data.</p>
                </div>
            <?php else: ?>
                <div class="amai-results-stat-row">
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number"><?php echo esc_html(number_format($ga4_sessions)); ?></div>
                        <div class="amai-results-stat-label">Visitors last 30 days</div>
                        <?php if ($ga4_delta !== null): ?>
                            <div class="amai-results-stat-delta <?php echo $ga4_delta >= 0 ? 'amai-results-delta--up' : 'amai-results-delta--down'; ?>">
                                <?php echo $ga4_delta >= 0 ? '+' : ''; ?><?php echo esc_html((string) $ga4_delta); ?>% vs prior period
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if (!empty($ga4_top_posts)): ?>
                    <div class="amai-results-top-posts">
                        <div class="amai-results-top-label">Top posts bringing people in</div>
                        <ul class="amai-results-post-list">
                            <?php foreach ($ga4_top_posts as $tp): ?>
                                <?php if (!is_array($tp)) { continue; } ?>
                                <li class="amai-results-post-item">
                                    <span class="amai-results-post-title"><?php echo esc_html((string) ($tp['post_title'] ?? '')); ?></span>
                                    <span class="amai-results-post-sessions"><?php echo esc_html(number_format((int) ($tp['sessions_30d'] ?? 0))); ?> visits</span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- SECTION: Content -->
        <div class="amai-results-card">
            <div class="amai-results-card-header">
                <span class="amai-results-eyebrow">Content</span>
                <h2 class="amai-results-card-title">Your content engine</h2>
            </div>
            <?php if ($blog_total === 0): ?>
                <div class="amai-results-empty">
                    <p class="amai-results-empty-text">No published blog posts yet. AutoMarketer AI will start generating them on your schedule.</p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai')); ?>" class="amai-results-cta">Go to Dashboard</a>
                </div>
            <?php else: ?>
                <div class="amai-results-stat-row">
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number"><?php echo esc_html((string) $blog_total); ?></div>
                        <div class="amai-results-stat-label">Published posts</div>
                    </div>
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number"><?php echo esc_html((string) $blog_posts_30d); ?></div>
                        <div class="amai-results-stat-label">New this month</div>
                    </div>
                </div>
                <div class="amai-results-proof-line">
                    Every post is a permanent asset that works for you around the clock.
                </div>
            <?php endif; ?>
        </div>

        <!-- SECTION: Social -->
        <div class="amai-results-card">
            <div class="amai-results-card-header">
                <span class="amai-results-eyebrow">Social Media</span>
                <h2 class="amai-results-card-title">Your social presence</h2>
            </div>
            <?php if (empty($channels_active)): ?>
                <div class="amai-results-empty">
                    <p class="amai-results-empty-text">No social channels connected yet. Connect Facebook, Instagram, or X to start posting automatically.</p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social')); ?>" class="amai-results-cta">Connect a Channel</a>
                </div>
            <?php else: ?>
                <div class="amai-results-stat-row">
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number"><?php echo esc_html((string) $posts_mtd); ?></div>
                        <div class="amai-results-stat-label">Posts this month</div>
                    </div>
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number"><?php echo esc_html((string) count($channels_active)); ?></div>
                        <div class="amai-results-stat-label"><?php echo count($channels_active) === 1 ? 'Active channel' : 'Active channels'; ?></div>
                    </div>
                </div>
                <div class="amai-results-channel-pills">
                    <?php foreach ($channels_active as $ch): ?>
                        <span class="amai-results-pill"><?php echo esc_html($ch); ?></span>
                    <?php endforeach; ?>
                </div>
                <?php if ($best_post !== null && is_array($best_post)): ?>
                    <div class="amai-results-best-post">
                        <div class="amai-results-best-label">Best post last 30 days</div>
                        <div class="amai-results-best-channel"><?php echo esc_html(ucfirst((string) ($best_post['channel'] ?? ''))); ?></div>
                        <div class="amai-results-best-content"><?php echo esc_html(mb_substr((string) ($best_post['content'] ?? ''), 0, 120)); ?><?php echo mb_strlen((string) ($best_post['content'] ?? '')) > 120 ? '...' : ''; ?></div>
                        <div class="amai-results-best-stats">
                            <?php if (!empty($best_post['stat_likes'])): ?>
                                <span><?php echo esc_html((string) $best_post['stat_likes']); ?> likes</span>
                            <?php endif; ?>
                            <?php if (!empty($best_post['stat_comments'])): ?>
                                <span><?php echo esc_html((string) $best_post['stat_comments']); ?> comments</span>
                            <?php endif; ?>
                            <?php if (!empty($best_post['stat_reach'])): ?>
                                <span><?php echo esc_html(number_format((int) $best_post['stat_reach'])); ?> reach</span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <!-- SECTION: Reputation -->
        <div class="amai-results-card">
            <div class="amai-results-card-header">
                <span class="amai-results-eyebrow">Reputation</span>
                <h2 class="amai-results-card-title">What people are saying</h2>
            </div>
            <?php if (!$reviews_exist || $review_count === 0): ?>
                <div class="amai-results-empty">
                    <?php if (!in_array('review-responder', (array) get_option('amai_active_modules', []), true)): ?>
                        <p class="amai-results-empty-text">Enable Review Responder to start tracking what customers are saying about your business.</p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-modules')); ?>" class="amai-results-cta">Enable Review Responder</a>
                    <?php else: ?>
                        <p class="amai-results-empty-text">No reviews collected yet. They'll appear here as they come in.</p>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <div class="amai-results-stat-row">
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number"><?php echo esc_html((string) $review_count); ?></div>
                        <div class="amai-results-stat-label">Total reviews</div>
                    </div>
                    <?php if ($avg_rating !== null): ?>
                        <div class="amai-results-stat">
                            <div class="amai-results-stat-number"><?php echo esc_html((string) $avg_rating); ?></div>
                            <div class="amai-results-stat-label">Average rating</div>
                            <?php echo amai_render_stars((float) $avg_rating); ?>
                        </div>
                    <?php endif; ?>
                </div>
                <?php if (!empty($recent_reviews)): ?>
                    <div class="amai-results-reviews">
                        <?php foreach ($recent_reviews as $rv): ?>
                            <?php if (!is_array($rv)) { continue; } ?>
                            <div class="amai-results-review-item">
                                <div class="amai-results-review-meta">
                                    <span class="amai-results-reviewer"><?php echo esc_html((string) ($rv['reviewer_name'] ?? 'Anonymous')); ?></span>
                                    <span class="amai-results-review-platform"><?php echo esc_html(ucfirst((string) ($rv['platform'] ?? ''))); ?></span>
                                </div>
                                <div class="amai-results-review-text">"<?php echo esc_html(mb_substr((string) ($rv['comment'] ?? ''), 0, 140)); ?><?php echo mb_strlen((string) ($rv['comment'] ?? '')) > 140 ? '...' : ''; ?>"</div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <?php if ($show_store && $store_connected): ?>
        <!-- SECTION: Store (product/mixed only) -->
        <div class="amai-results-card">
            <div class="amai-results-card-header">
                <span class="amai-results-eyebrow">Store</span>
                <h2 class="amai-results-card-title">Your store is converting</h2>
            </div>
            <?php if ($store_orders === 0): ?>
                <div class="amai-results-empty">
                    <p class="amai-results-empty-text">No completed orders in the last 30 days yet.</p>
                </div>
            <?php else: ?>
                <div class="amai-results-stat-row">
                    <div class="amai-results-stat">
                        <div class="amai-results-stat-number"><?php echo esc_html((string) $store_orders); ?></div>
                        <div class="amai-results-stat-label">Orders last 30 days</div>
                    </div>
                    <?php if ($store_revenue !== null && $store_revenue > 0): ?>
                        <div class="amai-results-stat-divider"></div>
                        <div class="amai-results-stat">
                            <div class="amai-results-stat-number"><?php echo esc_html(get_woocommerce_currency_symbol() . number_format($store_revenue, 2)); ?></div>
                            <div class="amai-results-stat-label">Revenue last 30 days</div>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

    </div><!-- .amai-results-grid -->
</div><!-- .amai-results-wrap -->