<?php
/**
 * Citation Dashboard Widget
 * Shows AI citation summary from SaaS
 * Only loads when user has enabled analytics (opt-in)
 */
class Shop2LLM_Citation_Widget {
    public static function init(): void {
        if (get_option('shop_to_llm_analytics', 'no') !== 'yes') return;
        add_action('wp_dashboard_setup', [self::class, 'add_dashboard_widget']);
    }

    public static function add_dashboard_widget(): void {
        wp_add_dashboard_widget(
            'shop2llm_citation_widget',
            'AI Citations — Shop2LLM',
            [self::class, 'render']
        );
    }

    public static function render(): void {
        $siteUrl = get_site_url();
        $domain = wp_parse_url($siteUrl, PHP_URL_HOST);

        // Try to get cached citation data
        $citationData = get_transient('shop2llm_citation_data');

        if (false === $citationData) {
            // Fetch from SaaS API (simple GET, no auth needed for summary endpoint)
            $response = wp_remote_get('https://api.shop2llm.com/fincore/v1/citation/results', [
                'timeout' => 5,
                'headers' => ['Authorization' => 'Bearer summary'],
            ]);
            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                $citationData = json_decode(wp_remote_retrieve_body($response), true);
                set_transient('shop2llm_citation_data', $citationData, HOUR_IN_SECONDS);
            }
        }

        $citedCount = 0;
        $totalChecks = 0;
        if (is_array($citationData) && isset($citationData['trackers'])) {
            foreach ($citationData['trackers'] as $tracker) {
                if (isset($tracker['cited']) && $tracker['cited']) $citedCount++;
                $totalChecks++;
            }
        }

        echo '<div style="padding:8px 0;">';

        if ($totalChecks > 0) {
            echo '<p style="font-size:24px;font-weight:700;margin:0 0 4px;color:#1d2327;">' . esc_html($citedCount) . ' <span style="font-size:14px;color:#646970;">citations this week</span></p>';
            echo '<p style="color:#646970;margin:0 0 12px;">Across ' . esc_html($totalChecks) . ' keyword checks</p>';
        } else {
            echo '<p style="color:#646970;">Track your AI citations across ChatGPT, Perplexity and more.</p>';
        }

        echo '<a href="https://shop2llm.com/dashboard" target="_blank" style="display:inline-block;background:#6366f1;color:#fff;padding:8px 16px;border-radius:6px;text-decoration:none;font-weight:600;font-size:13px;">View Full Report on Shop2LLM →</a>';
        echo '</div>';
    }
}
