<?php

/**
 * TrackSharp Dashboard
 * 
 * Handles the audit dashboard page.
 *
 * @package TrackSharp
 */
if (!defined('ABSPATH')) {
    exit;
}
class TrackSharp_Dashboard
{
    /** @var TrackSharp_Events_Log */
    private $events_log;

    /**
     * Constructor.
     *
     * @param TrackSharp_Events_Log $events_log Events logger.
     */
    public function __construct(TrackSharp_Events_Log $events_log)
    {
        $this->events_log = $events_log;
    }

    private function get_order_value($order): float
    {
        $total = (float) $order->get_total();
        if (!TrackSharp_Features::is_revenue_excl_tax()) {
            return $total;
        }

        $tax = (float) $order->get_total_tax();
        $value = $total - $tax;

        return ($value > 0) ? $value : 0.0;
    }

    /**
     * Render the dashboard page.
     *
     * @return void
     */
    public function render()
    {
        if (!current_user_can('manage_options')) {
            return;
        }
        global $wpdb;
        $table = $this->events_log->table_name();
        // Date range handling
        $allowed_ranges = [7, 30, 90];
        $range_days = (isset($_GET['ws_range']) ? (int) $_GET['ws_range'] : 30);
        if (!in_array($range_days, $allowed_ranges, true)) {
            $range_days = 30;
        }
        $range_label = sprintf('%d days', $range_days);
        $now_ts = time();
        $since_ts = $now_ts - $range_days * DAY_IN_SECONDS;
        $since = gmdate('Y-m-d H:i:s', $since_ts);
        $prev_start_ts = $since_ts - $range_days * DAY_IN_SECONDS;
        $prev_start = gmdate('Y-m-d H:i:s', $prev_start_ts);
        $prev_end = $since;
        // Get metrics
        $metrics = $this->calculate_metrics(
            $wpdb,
            $table,
            $since,
            $prev_start,
            $prev_end
        );
        // Generate sparklines
        $sparklines = $this->generate_sparklines($wpdb, $table, $since);
        $this->render_page(
            $range_days,
            $range_label,
            $allowed_ranges,
            $metrics,
            $sparklines
        );
    }

    /**
     * Calculate all metrics.
     */
    private function calculate_metrics(
        $wpdb,
        $table,
        $since,
        $prev_start,
        $prev_end
    ) {
        // Total tracked orders (GA4 only).
        //
        // Server-side purchases are the canonical baseline. In "browser-first + server fallback"
        // mode, some purchases may be tracked in the browser without a server purchase.
        // Only treat browser receipts as "tracked" when TrackSharp confirmed it actually sent a
        // browser GA4 purchase hit (audit receipt consent='sent').

        $server_txids = $wpdb->get_col($wpdb->prepare("\n            SELECT DISTINCT s.txid FROM {$table} s\n            WHERE s.channel = 'ga4' AND s.source = 'server' AND s.ok = 1\n            AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst')\n            AND s.ts >= %s\n        ", $since));
        $browser_txids = $wpdb->get_col($wpdb->prepare("\n            SELECT DISTINCT b.txid FROM {$table} b\n            WHERE b.channel = 'ga4' AND b.source = 'browser' AND b.ok = 1\n            AND b.txid IS NOT NULL AND b.event_name IN ('purchase','purchase_sst')\n            AND b.consent = 'sent'\n            AND b.ts >= %s\n        ", $since));
        $txids = array_values(array_unique(array_merge(is_array($server_txids) ? $server_txids : [], is_array($browser_txids) ? $browser_txids : [])));

        $prev_server_txids = $wpdb->get_col($wpdb->prepare("\n            SELECT DISTINCT s.txid FROM {$table} s\n            WHERE s.channel = 'ga4' AND s.source = 'server' AND s.ok = 1\n            AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst')\n            AND s.ts >= %s AND s.ts < %s\n        ", $prev_start, $prev_end));
        $prev_browser_txids = $wpdb->get_col($wpdb->prepare("\n            SELECT DISTINCT b.txid FROM {$table} b\n            WHERE b.channel = 'ga4' AND b.source = 'browser' AND b.ok = 1\n            AND b.txid IS NOT NULL AND b.event_name IN ('purchase','purchase_sst')\n            AND b.consent = 'sent'\n            AND b.ts >= %s AND b.ts < %s\n        ", $prev_start, $prev_end));
        $prev_txids = array_values(array_unique(array_merge(is_array($prev_server_txids) ? $prev_server_txids : [], is_array($prev_browser_txids) ? $prev_browser_txids : [])));

        $total_tracked = is_array($txids) ? count($txids) : 0;
        $total_tracked_prev = is_array($prev_txids) ? count($prev_txids) : 0;

        // Revenue requires WooCommerce orders.
        [$_ignored_count, $total_revenue] = $this->summarize_orders($txids);
        [$_ignored_prev_count, $total_revenue_prev] = $this->summarize_orders($prev_txids);

        // Proof/upsell metrics: detect Google Ads click IDs captured at checkout (gclid/gbraid/wbraid).
        $ads = $this->calculate_ads_click_metrics($txids);
        $ads_prev = $this->calculate_ads_click_metrics($prev_txids);
        // GA4 metrics
        $ga4 = $this->calculate_ga4_metrics(
            $wpdb,
            $table,
            $since,
            $prev_start,
            $prev_end
        );
        // Meta metrics
        $meta = $this->calculate_meta_metrics(
            $wpdb,
            $table,
            $since,
            $prev_start,
            $prev_end
        );
        return [
            'total_tracked' => $total_tracked,
            'total_tracked_prev' => $total_tracked_prev,
            'total_revenue' => $total_revenue,
            'total_revenue_prev' => $total_revenue_prev,
            'ga4' => $ga4,
            'meta' => $meta,
            'ads' => $ads,
            'ads_prev' => $ads_prev,
        ];
    }

    /**
     * Calculate metrics for GA4.
     */
    private function calculate_ga4_metrics(
        $wpdb,
        $table,
        $since,
        $prev_start,
        $prev_end
    ) {
        // Browser purchase detection: simply check for any browser purchase event in the log.
        // This is mode-agnostic - the dashboard shows actual browser coverage regardless of
        // which attribution mode is currently selected.

        $browser_tracked = (int) $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(DISTINCT b.txid) FROM {$table} b
            WHERE b.channel='ga4' AND b.source='browser' AND b.ok=1
            AND b.txid IS NOT NULL AND b.event_name IN ('purchase','purchase_sst')
            AND b.ts >= %s
        ", $since));
        $browser_tracked_prev = (int) $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(DISTINCT b.txid) FROM {$table} b
            WHERE b.channel='ga4' AND b.source='browser' AND b.ok=1
            AND b.txid IS NOT NULL AND b.event_name IN ('purchase','purchase_sst')
            AND b.ts >= %s AND b.ts < %s
        ", $prev_start, $prev_end));

        // Rescued = orders that would have been missed by GTM, either because:
        // 1. Marketing consent was denied (GTM requires marketing consent), OR
        // 2. Browser event never fired (blocked by ad blockers, page exit, etc.)
        $rescued = (int) $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(DISTINCT s.txid) FROM {$table} s
            WHERE s.channel='ga4' AND s.source='server' AND s.ok=1
            AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst') AND s.ts >= %s
            AND (
                s.consent='denied'
                OR NOT EXISTS (
                    SELECT 1 FROM {$table} b
                    WHERE b.channel='ga4' AND b.source='browser' AND b.event_name IN ('purchase','purchase_sst')
                    AND b.txid = s.txid AND b.ts >= %s
                )
            )
        ", $since, $since));
        $rescued_prev = (int) $wpdb->get_var($wpdb->prepare(
            "
            SELECT COUNT(DISTINCT s.txid) FROM {$table} s
            WHERE s.channel='ga4' AND s.source='server' AND s.ok=1
            AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst')
            AND s.ts >= %s AND s.ts < %s
            AND (
                s.consent='denied'
                OR NOT EXISTS (
                    SELECT 1 FROM {$table} b
                    WHERE b.channel='ga4' AND b.source='browser' AND b.event_name IN ('purchase','purchase_sst')
                    AND b.txid = s.txid AND b.ts >= %s AND b.ts < %s
                )
            )
        ",
            $prev_start,
            $prev_end,
            $prev_start,
            $prev_end
        ));
        // Both (server + browser)
        $both = (int) $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(DISTINCT s.txid) FROM {$table} s
            WHERE s.channel='ga4' AND s.source='server' AND s.ok=1
            AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst') AND s.ts >= %s
            AND (s.consent IS NULL OR s.consent <> 'denied')
            AND EXISTS (
                SELECT 1 FROM {$table} b
                WHERE b.channel='ga4' AND b.source='browser' AND b.event_name IN ('purchase','purchase_sst')
                AND b.txid = s.txid AND b.ts >= %s
            )
        ", $since, $since));
        $both_prev = (int) $wpdb->get_var($wpdb->prepare(
            "
            SELECT COUNT(DISTINCT s.txid) FROM {$table} s
            WHERE s.channel='ga4' AND s.source='server' AND s.ok=1
            AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst')
            AND s.ts >= %s AND s.ts < %s
            AND (s.consent IS NULL OR s.consent <> 'denied')
            AND EXISTS (
                SELECT 1 FROM {$table} b
                WHERE b.channel='ga4' AND b.source='browser' AND b.event_name IN ('purchase','purchase_sst')
                AND b.txid = s.txid AND b.ts >= %s AND b.ts < %s
            )
        ",
            $prev_start,
            $prev_end,
            $prev_start,
            $prev_end
        ));
        // Calculate rescued revenue by joining with WooCommerce order totals
        $rescued_revenue = 0.0;
        $rescued_revenue_prev = 0.0;
        if (function_exists('wc_get_order')) {
            // Get rescued order IDs (current period)
            $rescued_order_ids = $wpdb->get_col($wpdb->prepare("
                SELECT DISTINCT s.txid FROM {$table} s
                WHERE s.channel='ga4' AND s.source='server' AND s.ok=1
                AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst') AND s.ts >= %s
                AND (
                    s.consent='denied'
                    OR NOT EXISTS (
                        SELECT 1 FROM {$table} b
                        WHERE b.channel='ga4' AND b.source='browser' AND b.event_name IN ('purchase','purchase_sst')
                        AND b.txid = s.txid AND b.ts >= %s
                    )
                )
            ", $since, $since));
            foreach ($rescued_order_ids as $order_id) {
                $order = wc_get_order((int) $order_id);
                if ($order) {
                    $rescued_revenue += $this->get_order_value($order);
                }
            }
            // Get rescued order IDs (previous period)
            $rescued_order_ids_prev = $wpdb->get_col($wpdb->prepare(
                "
                SELECT DISTINCT s.txid FROM {$table} s
                WHERE s.channel='ga4' AND s.source='server' AND s.ok=1
                AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst')
                AND s.ts >= %s AND s.ts < %s
                AND (
                    s.consent='denied'
                    OR NOT EXISTS (
                        SELECT 1 FROM {$table} b
                        WHERE b.channel='ga4' AND b.source='browser' AND b.event_name IN ('purchase','purchase_sst')
                        AND b.txid = s.txid AND b.ts >= %s AND b.ts < %s
                    )
                )
            ",
                $prev_start,
                $prev_end,
                $prev_start,
                $prev_end
            ));
            foreach ($rescued_order_ids_prev as $order_id) {
                $order = wc_get_order((int) $order_id);
                if ($order) {
                    $rescued_revenue_prev += $this->get_order_value($order);
                }
            }
        }
        return [
            'rescued' => $rescued,
            'rescued_prev' => $rescued_prev,
            'rescued_revenue' => $rescued_revenue,
            'rescued_revenue_prev' => $rescued_revenue_prev,
            'both' => $both,
            'both_prev' => $both_prev,
            'server_tracked' => $rescued + $both,
            'server_tracked_prev' => $rescued_prev + $both_prev,
            'browser_tracked' => $browser_tracked,
            'browser_tracked_prev' => $browser_tracked_prev,
        ];
    }

    /**
     * Calculate metrics for Meta.
     */
    private function calculate_meta_metrics(
        $wpdb,
        $table,
        $since,
        $prev_start,
        $prev_end
    ) {
        // Browser pixel coverage (audit-only): indicates whether fbq actually fired for Purchase.
        $browser_tracked = (int) $wpdb->get_var($wpdb->prepare("\n            SELECT COUNT(DISTINCT b.txid) FROM {$table} b\n            WHERE b.channel='meta' AND b.source='browser' AND b.ok=1\n            AND b.txid IS NOT NULL AND b.event_name IN ('Purchase') AND b.ts >= %s\n        ", $since));
        $browser_tracked_prev = (int) $wpdb->get_var($wpdb->prepare(
            "\n            SELECT COUNT(DISTINCT b.txid) FROM {$table} b\n            WHERE b.channel='meta' AND b.source='browser' AND b.ok=1\n            AND b.txid IS NOT NULL AND b.event_name IN ('Purchase')\n            AND b.ts >= %s AND b.ts < %s\n        ",
            $prev_start,
            $prev_end
        ));

        $rescued = (int) $wpdb->get_var($wpdb->prepare("\n            SELECT COUNT(DISTINCT s.txid) FROM {$table} s\n            WHERE s.channel='meta' AND s.source='server' AND s.ok=1\n            AND s.txid IS NOT NULL AND s.event_name IN ('Purchase') AND s.ts >= %s\n            AND (\n                s.consent='denied'\n                OR NOT EXISTS (\n                    SELECT 1 FROM {$table} b\n                    WHERE b.channel='meta' AND b.source='browser' AND b.event_name IN ('Purchase')\n                    AND b.txid = s.txid AND b.ts >= %s\n                )\n            )\n        ", $since, $since));
        $rescued_prev = (int) $wpdb->get_var($wpdb->prepare(
            "\n            SELECT COUNT(DISTINCT s.txid) FROM {$table} s\n            WHERE s.channel='meta' AND s.source='server' AND s.ok=1\n            AND s.txid IS NOT NULL AND s.event_name IN ('Purchase')\n            AND s.ts >= %s AND s.ts < %s\n            AND (\n                s.consent='denied'\n                OR NOT EXISTS (\n                    SELECT 1 FROM {$table} b\n                    WHERE b.channel='meta' AND b.source='browser' AND b.event_name IN ('Purchase')\n                    AND b.txid = s.txid AND b.ts >= %s AND b.ts < %s\n                )\n            )\n        ",
            $prev_start,
            $prev_end,
            $prev_start,
            $prev_end
        ));
        $both = (int) $wpdb->get_var($wpdb->prepare("\n            SELECT COUNT(DISTINCT s.txid) FROM {$table} s\n            WHERE s.channel='meta' AND s.source='server' AND s.ok=1\n            AND s.txid IS NOT NULL AND s.event_name IN ('Purchase') AND s.ts >= %s\n            AND EXISTS (\n                SELECT 1 FROM {$table} b\n                WHERE b.channel='meta' AND b.source='browser' AND b.event_name IN ('Purchase')\n                AND b.txid = s.txid AND b.ts >= %s\n            )\n        ", $since, $since));
        $both_prev = (int) $wpdb->get_var($wpdb->prepare(
            "\n            SELECT COUNT(DISTINCT s.txid) FROM {$table} s\n            WHERE s.channel='meta' AND s.source='server' AND s.ok=1\n            AND s.txid IS NOT NULL AND s.event_name IN ('Purchase')\n            AND s.ts >= %s AND s.ts < %s\n            AND EXISTS (\n                SELECT 1 FROM {$table} b\n                WHERE b.channel='meta' AND b.source='browser' AND b.event_name IN ('Purchase')\n                AND b.txid = s.txid AND b.ts >= %s AND b.ts < %s\n            )\n        ",
            $prev_start,
            $prev_end,
            $prev_start,
            $prev_end
        ));
        $rescued_revenue = 0.0;
        $rescued_revenue_prev = 0.0;
        if (function_exists('wc_get_order')) {
            $rescued_order_ids = $wpdb->get_col($wpdb->prepare("\n                SELECT DISTINCT s.txid FROM {$table} s\n                WHERE s.channel='meta' AND s.source='server' AND s.ok=1\n                AND s.txid IS NOT NULL AND s.event_name IN ('Purchase') AND s.ts >= %s\n                AND (\n                    s.consent='denied'\n                    OR NOT EXISTS (\n                        SELECT 1 FROM {$table} b\n                        WHERE b.channel='meta' AND b.source='browser' AND b.event_name IN ('Purchase')\n                        AND b.txid = s.txid AND b.ts >= %s\n                    )\n                )\n            ", $since, $since));
            foreach ($rescued_order_ids as $order_id) {
                $order = wc_get_order((int) $order_id);
                if ($order) {
                    $rescued_revenue += $this->get_order_value($order);
                }
            }
            $rescued_order_ids_prev = $wpdb->get_col($wpdb->prepare(
                "\n                SELECT DISTINCT s.txid FROM {$table} s\n                WHERE s.channel='meta' AND s.source='server' AND s.ok=1\n                AND s.txid IS NOT NULL AND s.event_name IN ('Purchase')\n                AND s.ts >= %s AND s.ts < %s\n                AND (\n                    s.consent='denied'\n                    OR NOT EXISTS (\n                        SELECT 1 FROM {$table} b\n                        WHERE b.channel='meta' AND b.source='browser' AND b.event_name IN ('Purchase')\n                        AND b.txid = s.txid AND b.ts >= %s AND b.ts < %s\n                    )\n                )\n            ",
                $prev_start,
                $prev_end,
                $prev_start,
                $prev_end
            ));
            foreach ($rescued_order_ids_prev as $order_id) {
                $order = wc_get_order((int) $order_id);
                if ($order) {
                    $rescued_revenue_prev += $this->get_order_value($order);
                }
            }
        }
        return [
            'rescued' => $rescued,
            'rescued_prev' => $rescued_prev,
            'rescued_revenue' => $rescued_revenue,
            'rescued_revenue_prev' => $rescued_revenue_prev,
            'both' => $both,
            'both_prev' => $both_prev,
            'server_tracked' => $rescued + $both,
            'server_tracked_prev' => $rescued_prev + $both_prev,
        ];
    }

    /**
     * Generate sparkline data.
     */
    private function generate_sparklines($wpdb, $table, $since)
    {
        // Sparkline shows rescued purchases per day.
        // Mode-agnostic: simply check for any browser purchase event in the log.
        $ga4_rows = $wpdb->get_results($wpdb->prepare("
            SELECT DATE(s.ts) AS d, COUNT(DISTINCT s.txid) AS c
            FROM {$table} s
            WHERE s.channel='ga4' AND s.source='server' AND s.ok=1
            AND s.txid IS NOT NULL AND s.event_name IN ('purchase','purchase_sst') AND s.ts >= %s
            AND (
                s.consent='denied'
                OR NOT EXISTS (
                    SELECT 1 FROM {$table} b
                    WHERE b.channel='ga4' AND b.source='browser' AND b.event_name IN ('purchase','purchase_sst')
                    AND b.txid = s.txid AND b.ts >= %s
                )
            )
            GROUP BY DATE(s.ts) ORDER BY d ASC
        ", $since, $since), ARRAY_A);
        $meta_rows = $wpdb->get_results($wpdb->prepare("
            SELECT DATE(s.ts) AS d, COUNT(DISTINCT s.txid) AS c
            FROM {$table} s
            WHERE s.channel='meta' AND s.source='server' AND s.ok=1
            AND s.txid IS NOT NULL AND s.event_name IN ('Purchase') AND s.ts >= %s
            AND NOT EXISTS (
                SELECT 1 FROM {$table} b
                WHERE b.channel='meta' AND b.source='browser' AND b.event_name IN ('Purchase')
                AND b.txid = s.txid AND b.ts >= %s
            )
            GROUP BY DATE(s.ts) ORDER BY d ASC
        ", $since, $since), ARRAY_A);
        return [
            'ga4' => $this->build_sparkline($ga4_rows),
            'meta' => $this->build_sparkline($meta_rows),
        ];
    }

    /**
     * Build sparkline SVG data.
     */
    private function build_sparkline($rows)
    {
        $w = 340;
        $h = 60;
        $pad = 8;
        $points = [];
        $labels = [];
        $max = 0;
        foreach ($rows as $r) {
            $labels[] = $r['d'];
            $c = (int) $r['c'];
            $max = max($max, $c);
        }
        $n = max(1, count($rows));
        $stepX = ($w - 2 * $pad) / max(1, $n - 1);
        foreach ($rows as $i => $r) {
            $c = (int) $r['c'];
            $x = $pad + $i * $stepX;
            $y = $pad + ($h - 2 * $pad) * (1 - (($max ? $c / $max : 0)));
            $points[] = round($x, 1) . ',' . round($y, 1);
        }
        return [
            'polyline' => ($points ? implode(' ', $points) : ''),
            'points' => $points,
            'labels' => $labels,
            'max' => $max,
            'w' => $w,
            'h' => $h,
        ];
    }

    /**
     * Summarize orders.
     */
    private function summarize_orders(array $order_ids): array
    {
        $count = 0;
        $total = 0.0;
        $allowed_statuses = [
            'processing',
            'completed',
            'on-hold',
            'refunded',
            'cancelled',
            'failed',
            'pending'
        ];
        if (!$order_ids || !function_exists('wc_get_order')) {
            return [$count, $total];
        }
        foreach ($order_ids as $oid) {
            $order = wc_get_order($oid);
            if (!$order) {
                continue;
            }
            if (!in_array($order->get_status(), $allowed_statuses, true)) {
                continue;
            }
            $count++;
            $total += $this->get_order_value($order);
        }
        return [$count, $total];
    }

    /**
     * Calculate revenue from orders that have Google Ads click IDs captured at checkout.
     *
     * @param array $order_ids Order IDs (transaction IDs).
     * @return array{count:int,revenue:float}
     */
    private function calculate_ads_click_metrics(array $order_ids): array
    {
        $count = 0;
        $revenue = 0.0;

        $allowed_statuses = [
            'processing',
            'completed',
            'on-hold',
            'refunded',
            'cancelled',
            'failed',
            'pending'
        ];

        if (!$order_ids || !function_exists('wc_get_order')) {
            return ['count' => 0, 'revenue' => 0.0];
        }

        foreach ($order_ids as $oid) {
            $order = wc_get_order($oid);
            if (!$order) {
                continue;
            }
            if (!in_array($order->get_status(), $allowed_statuses, true)) {
                continue;
            }

            $gclid = (string) $order->get_meta('_ws_gclid');
            $gbraid = (string) $order->get_meta('_ws_gbraid');
            $wbraid = (string) $order->get_meta('_ws_wbraid');

            if ($gclid === '' && $gbraid === '' && $wbraid === '') {
                continue;
            }

            $count++;
            $revenue += $this->get_order_value($order);
        }

        return ['count' => $count, 'revenue' => $revenue];
    }

    /**
     * Render delta badge.
     */
    private function render_delta_badge($current, $previous, callable $formatter = null): string
    {
        $diff = $current - $previous;
        if (abs($diff) < 1.0E-5) {
            return '<span class="ws-delta ws-flat">=&nbsp;vs. previous period</span>';
        }
        $class = ($diff > 0 ? 'ws-up' : 'ws-down');
        if (!$formatter) {
            $formatted = number_format_i18n((int) abs(round($diff)));
        } else {
            $formatted = call_user_func($formatter, abs($diff));
        }
        $sign = ($diff > 0 ? '+' : '-');
        return '<span class="ws-delta ' . $class . '">' . $sign . $formatted . '&nbsp;vs. previous period</span>';
    }

    /**
     * Render the page HTML.
     */
    private function render_page(
        $range_days,
        $range_label,
        $allowed_ranges,
        $metrics,
        $sparklines
    ) {
        ?>
        <div class="wrap tracksharp-admin">
            <div class="ws-card">
                <div class="ws-card-header">
                    <div>
                        <h1>TrackSharp Dashboard</h1>
                        <p class="ws-desc">Server-to-server results over <?php
                        echo esc_html($range_label);
                        ?>.</p>
                    </div>
                    <div class="ws-toolbar">
                        <a class="button" href="<?php
                        echo esc_url(admin_url('admin.php?page=tracksharp-setup'));
                        ?>">Setup
                            Wizard</a>
                        <a class="button" href="<?php
                        echo esc_url(admin_url('admin.php?page=tracksharp-events'));
                        ?>">Event
                            Log</a>
                        <form method="get" class="ws-range">
                            <input type="hidden" name="page" value="tracksharp-audit" />
                            <label for="ws-range-select">Period</label>
                            <select id="ws-range-select" name="ws_range" onchange="this.form.submit()">
                                <?php
                                foreach ($allowed_ranges as $days) {
                                    ?>
                                    <option value="<?php
                                    echo esc_attr($days);
                                    ?>" <?php
                                    selected($range_days, $days);
                                    ?>>
                                        <?php
                                        echo esc_html(sprintf('%d days', $days));
                                        ?>
                                    </option>
                                    <?php
                                }
                                ?>
                            </select>
                        </form>
                    </div>
                </div>
            </div>

            <div class="ws-grid ws-grid-3">
                <div class="ws-card">
                    <p class="ws-desc">Orders tracked (<?php
                    echo esc_html($range_label);
                    ?>)</p>
                    <div class="ws-metric-value"><?php
                    echo esc_html(number_format_i18n($metrics['total_tracked']));
                    ?></div>
                    <?php
                    echo wp_kses_post($this->render_delta_badge($metrics['total_tracked'], $metrics['total_tracked_prev']));
                    ?>
                </div>
                <div class="ws-card">
                    <p class="ws-desc">Revenue tracked (<?php
                    echo esc_html($range_label);
                    ?>)</p>
                    <div class="ws-metric-value">
                        <?php
                        echo wp_kses_post((function_exists('wc_price') ? wc_price($metrics['total_revenue']) : '€' . number_format($metrics['total_revenue'], 2)));
                        ?>
                    </div>
                    <?php
                    echo wp_kses_post($this->render_delta_badge($metrics['total_revenue'], $metrics['total_revenue_prev'], function ($amount) {
                        return (function_exists('wc_price') ? wc_price($amount) : '€' . number_format($amount, 2));
                    }));
                    ?>
                </div>
                <div class="ws-card"
                    style="background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%); border: 1px solid #bbf7d0;">
                    <p class="ws-desc" style="color:#166534;">Rescued Revenue (<?php
                    echo esc_html($range_label);
                    ?>)</p>
                    <div class="ws-metric-value" style="color:#158a5f;">
                        <?php
                        echo wp_kses_post((function_exists('wc_price') ? wc_price($metrics['ga4']['rescued_revenue']) : '€' . number_format($metrics['ga4']['rescued_revenue'], 2)));
                        ?>
                    </div>
                    <?php
                    echo wp_kses_post($this->render_delta_badge($metrics['ga4']['rescued_revenue'], $metrics['ga4']['rescued_revenue_prev'], function ($amount) {
                        return (function_exists('wc_price') ? wc_price($amount) : '€' . number_format($amount, 2));
                    }));
                    ?>
                    <p class="ws-note" style="color:#15803d;">Revenue that would be lost without server tracking</p>
                </div>
            </div>

            <?php $this->render_proof_upsell_cards($range_label, $metrics); ?>

            <?php
            // GA4 card is always visible - this is the core value proposition
            $this->render_channel_card(
                'Google Analytics 4',
                'ga4',
                $range_label,
                $metrics['ga4'],
                $sparklines['ga4']
            );
            ?>

            <?php
            if (TrackSharp_Features::is_meta_available()) {
                ?>
                <?php
                $this->render_channel_card(
                    'Meta (CAPI vs Pixel)',
                    'meta',
                    $range_label,
                    $metrics['meta'],
                    $sparklines['meta']
                );
                ?>
                <?php
            } else {
                ?>
                <?php
                echo wp_kses_post(TrackSharp_Features::render_upgrade_prompt(__('Meta Conversions API (Pro)', 'tracksharp'), __('Meta server-side tracking is available in TrackSharp Pro.', 'tracksharp')));
                ?>
                <?php
            }
            ?>
        </div>
        <?php
    }

    /**
     * Render "proof" cards that make the Pro value obvious using the site's own data.
     *
     * @param string $range_label Range label (e.g. "30 days").
     * @param array  $metrics     Metrics array.
     * @return void
     */
    private function render_proof_upsell_cards($range_label, $metrics)
    {
        if (TrackSharp_Features::is_pro_active()) {
            return;
        }

        $upgrade_url = TrackSharp_Features::get_upgrade_url();
        $events_url = admin_url('admin.php?page=tracksharp-events');

        $ads = isset($metrics['ads']) && is_array($metrics['ads']) ? $metrics['ads'] : ['count' => 0, 'revenue' => 0.0];
        $meta = isset($metrics['meta']) && is_array($metrics['meta']) ? $metrics['meta'] : [];

        $ads_count = (int) ($ads['count'] ?? 0);
        $ads_revenue = (float) ($ads['revenue'] ?? 0.0);
        $meta_browser = (int) ($meta['browser_tracked'] ?? 0);
        $has_ads_clicks = ($ads_count > 0);
        $has_meta_pixel_purchases = ($meta_browser > 0);

        $ga4_filter_url = add_query_arg(
            [
                'channel' => 'ga4',
                'source' => 'server',
                'event' => TrackSharp_Features::ga4_purchase_event_name(),
            ],
            $events_url
        );

        $meta_filter_url = add_query_arg(
            [
                'channel' => 'meta',
                'source' => 'browser',
                'event' => 'Purchase',
            ],
            $events_url
        );
        ?>
        <div class="ws-grid ws-grid-2 ws-proof-grid" style="margin-top: 18px; padding-bottom: 22px; margin-bottom: 48px;">
            <div class="ws-card" style="border:1px solid #fde68a;background:linear-gradient(135deg,#fffbeb 0%,#fef3c7 100%);">
                <div class="ws-card-header">
                    <div>
                        <h2 style="margin:0;color:#92400e;">Revenue from ads you can't attribute</h2>
                        <p class="ws-desc" style="margin:6px 0 0;color:#92400e;">
                            <?php if ($has_ads_clicks): ?>
                                TrackSharp detected Google Ads clicks on real orders in the last
                                <?php echo esc_html($range_label); ?>.
                                Without Pro, server-side purchases can't be attributed back to Google Ads when browser tags are
                                blocked.
                            <?php else: ?>
                                No orders were matched to Google Ads clicks in the last <?php echo esc_html($range_label); ?>.
                                If you run Google Ads, enable auto-tagging and confirm traffic reaches checkout to see attribution
                                opportunities here.
                            <?php endif; ?>
                        </p>
                    </div>
                    <span class="ws-tag"
                        style="background:#fffbeb;color:#92400e;border:1px solid #fde68a;"><?php echo esc_html($range_label); ?></span>
                </div>

                <div class="ws-grid ws-grid-2" style="margin-top:12px;gap:12px;">
                    <div>
                        <p class="ws-desc" style="margin:0;color:#92400e;">Orders matched to Google Ads</p>
                        <div class="ws-metric-value" style="color:#92400e;">
                            <?php echo esc_html(number_format_i18n($ads_count)); ?>
                        </div>
                    </div>
                    <div>
                        <p class="ws-desc" style="margin:0;color:#92400e;">Ad-driven revenue</p>
                        <div class="ws-metric-value" style="color:#92400e;">
                            <?php echo wp_kses_post(function_exists('wc_price') ? wc_price($ads_revenue) : number_format($ads_revenue, 2)); ?>
                        </div>
                    </div>
                </div>

                <p class="ws-note" style="margin-top:10px;color:#92400e;">
                    Pro unlocks server-side Google Ads attribution so conversions can be credited correctly even when browser
                    tags don't fire.
                </p>

                <div class="ws-proof-actions">
                    <a class="button button-primary" href="<?php echo esc_url($upgrade_url); ?>"
                        style="background:#b45309;border-color:#92400e;">
                        Unlock Google Ads attribution (Pro)
                    </a>
                    <a class="button" href="<?php echo esc_url($ga4_filter_url); ?>"
                        style="border-color:#92400e;color:#92400e;">
                        View GA4 purchase logs
                    </a>
                </div>
            </div>

            <div class="ws-card" style="border:1px solid #c7d2fe;background:linear-gradient(135deg,#eef2ff 0%,#e0e7ff 100%);">
                <div class="ws-card-header">
                    <div>
                        <h2 style="margin:0;color:#3730a3;">Meta tracking status: Browser-only</h2>
                        <p class="ws-desc" style="margin:6px 0 0;color:#3730a3;">
                            Your setup relies 100% on the browser Pixel. iOS privacy and ad blockers can prevent purchases from
                            being tracked.
                            Add server-side (CAPI) to secure this data and improve match quality.
                        </p>
                    </div>
                    <span class="ws-tag"
                        style="background:#eef2ff;color:#3730a3;border:1px solid #c7d2fe;"><?php echo esc_html($range_label); ?></span>
                </div>

                <div class="ws-grid ws-grid-2" style="margin-top:12px;gap:12px;">
                    <div>
                        <p class="ws-desc" style="margin:0;color:#3730a3;">Pixel purchases detected (browser)</p>
                        <div class="ws-metric-value" style="color:#3730a3;">
                            <?php echo esc_html(number_format_i18n($meta_browser)); ?>
                        </div>
                    </div>
                    <div>
                        <p class="ws-desc" style="margin:0;color:#3730a3;">Server-side purchases (CAPI)</p>
                        <div class="ws-metric-value" style="color:#3730a3;font-size:18px;line-height:1.3;margin-top:4px;">
                            Not enabled (Pro)
                        </div>
                    </div>
                </div>

                <p class="ws-note" style="color:#3730a3;margin-top:6px;">
                    <?php if ($has_meta_pixel_purchases): ?>
                        Pro adds server-side Purchase + hashing to improve match quality and fill gaps when the Pixel can't fire.
                    <?php else: ?>
                        If you expected Pixel purchases here, open the log to verify the Pixel is installed and consent allows
                        marketing cookies. Pro then adds the server-side safety net.
                    <?php endif; ?>
                </p>

                <div class="ws-proof-actions">
                    <a class="button button-primary" href="<?php echo esc_url($upgrade_url); ?>"
                        style="background:#4338ca;border-color:#3730a3;">
                        Enable Meta CAPI (Pro)
                    </a>
                    <a class="button" href="<?php echo esc_url($meta_filter_url); ?>"
                        style="border-color:#3730a3;color:#3730a3;">
                        View Pixel purchase logs
                    </a>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render channel metrics card.
     */
    private function render_channel_card(
        $title,
        $channel,
        $range_label,
        $metrics,
        $sparkline
    ) {
        // For GA4, check the attribution mode to show contextual labels
        $ga4_mode = ($channel === 'ga4') ? TrackSharp_Features::ga4_attribution_mode() : 'ads_first';
        $is_browser_first = ($ga4_mode === 'reporting_first');
        ?>
        <div class="ws-card">
            <div class="ws-card-header">
                <div>
                    <h2><?php
                    echo esc_html($title);
                    ?></h2>
                    <p class="ws-desc">
                        <?php
                        if ($channel === 'ga4') {
                            echo $is_browser_first
                                ? 'Browser-first mode: server fires only as fallback.'
                                : 'Server-to-server vs. browser hits.';
                        } else {
                            echo 'Check for deduplicated pixel hits.';
                        }
                        ?>
                    </p>
                </div>
                <span class="ws-tag"><?php
                echo esc_html($range_label);
                ?></span>
            </div>
            <div class="ws-grid ws-grid-3">
                <div>
                    <p class="ws-desc"><?php echo $is_browser_first ? 'Browser purchases' : 'Orders with server hit'; ?></p>
                    <div class="ws-metric-value"><?php
                    echo esc_html(number_format_i18n($is_browser_first ? ($metrics['browser_tracked'] ?? 0) : $metrics['server_tracked']));
                    ?></div>
                    <?php
                    echo wp_kses_post($this->render_delta_badge(
                        $is_browser_first ? ($metrics['browser_tracked'] ?? 0) : $metrics['server_tracked'],
                        $is_browser_first ? ($metrics['browser_tracked_prev'] ?? 0) : $metrics['server_tracked_prev']
                    ));
                    ?>
                    <?php if ($is_browser_first): ?>
                        <p class="ws-note">Orders tracked via browser GA4.</p>
                    <?php endif; ?>
                </div>
                <div>
                    <p class="ws-desc">Rescued (server only)</p>
                    <div class="ws-metric-value"><?php
                    echo esc_html(number_format_i18n($metrics['rescued']));
                    ?></div>
                    <?php
                    echo wp_kses_post($this->render_delta_badge($metrics['rescued'], $metrics['rescued_prev']));
                    ?>
                    <p class="ws-note"><?php echo $is_browser_first
                        ? 'Server fallback fired when browser failed.'
                        : 'Orders that would be lost without server hit.'; ?></p>
                </div>
                <div>
                    <?php if ($is_browser_first && $channel === 'ga4'): ?>
                        <p class="ws-desc">Server fallbacks</p>
                        <div class="ws-metric-value"><?php
                        echo esc_html(number_format_i18n($metrics['server_tracked']));
                        ?></div>
                        <?php
                        echo wp_kses_post($this->render_delta_badge($metrics['server_tracked'], $metrics['server_tracked_prev']));
                        ?>
                        <p class="ws-note">Total server-side events (rescued + potential duplicates).</p>
                    <?php else: ?>
                        <p class="ws-desc">Server + <?php
                        echo ($channel === 'ga4' ? 'browser' : 'pixel');
                        ?></p>
                        <div class="ws-metric-value"><?php
                        echo esc_html(number_format_i18n($metrics['both']));
                        ?></div>
                        <?php
                        echo wp_kses_post($this->render_delta_badge($metrics['both'], $metrics['both_prev']));
                        ?>
                        <p class="ws-note">
                            <?php
                            echo ($channel === 'ga4' ? 'Browser and server confirm the same order.' : 'Confirmed by both pixel and server.');
                            ?>
                        </p>
                    <?php endif; ?>
                </div>
            </div>
            <div class="ws-sparkline">
                <strong>Rescued per day</strong>
                <svg width="<?php
                echo esc_attr($sparkline['w']);
                ?>" height="<?php
                echo esc_attr($sparkline['h']);
                ?>" viewBox="0 0 <?php
                echo esc_attr($sparkline['w']);
                ?> <?php
                 echo esc_attr($sparkline['h']);
                 ?>">
                    <rect x="0" y="0" width="<?php
                    echo esc_attr($sparkline['w']);
                    ?>" height="<?php
                    echo esc_attr($sparkline['h']);
                    ?>" fill="#fff" />
                    <?php
                    if ($sparkline['polyline']) {
                        ?>
                        <polyline points="<?php
                        echo esc_attr($sparkline['polyline']);
                        ?>" fill="none" stroke="#158a5f" stroke-width="2" />
                        <?php
                        foreach ($sparkline['points'] as $pt) {
                            list($dx, $dy) = array_map('floatval', explode(',', $pt));
                            echo '<circle cx="' . esc_attr($dx) . '" cy="' . esc_attr($dy) . '" r="2" fill="#158a5f"/>';
                        }
                        ?>
                        <?php
                    } else {
                        ?>
                        <text x="12" y="34" fill="#64748b">No rescued purchases yet</text>
                        <?php
                    }
                    ?>
                </svg>
                <p class="ws-note">
                    <?php
                    echo ($sparkline['max'] ? 'Peak day: ' . esc_html(max($sparkline['labels'])) . ' (' . esc_html($sparkline['max']) . ')' : '--');
                    ?>
                </p>
            </div>
        </div>
        <?php
    }

}
