<?php
/**
 * AI Crawlers Tab
 *
 * Surfaces the server-side AI-crawler data collected by kantan_log_ai_crawler_hit()
 * (see includes/api.php). AI crawlers — GPTBot, ClaudeBot, PerplexityBot, CCBot,
 * and friends — fetch pages without running JavaScript, so they never appear in
 * the JS-beacon-based human metrics. This tab gives them their own view so a
 * site owner can answer "is my content being crawled by AI, and which pages?"
 * without those bot hits ever polluting human visitor stats.
 *
 * Basic counts are free. The trend-over-time and AEO ("are the RIGHT pages being
 * crawled?") layer is the Kantan SEO upsell — shown only when SEO isn't active,
 * intensity gated by the distribution channel (see KANTAN_ANALYTICS_CHANNEL).
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Register the AI Crawlers tab, inserted just before Settings in the Analytics
 * group. Priority 6 so it lands right after the Conversions tab (priority 5).
 */
function kantan_register_ai_crawlers_tab($tabs) {
    $entry = array(
        'ai-crawlers' => array(
            'label' => __('AI Crawlers', 'kantan-analytics'),
            'group' => __('Analytics', 'kantan-analytics'),
            'icon'  => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"></path>',
        ),
    );

    $pos = array_search('settings', array_keys($tabs), true);
    if ($pos === false) {
        return $tabs + $entry;
    }
    return array_slice($tabs, 0, $pos, true) + $entry + array_slice($tabs, $pos, null, true);
}
add_filter('kantan_analytics_dashboard_tabs', 'kantan_register_ai_crawlers_tab', 6);

/**
 * Render the AI Crawlers tab body. Hooked to the dashboard's companion-tab
 * render action; bails for any other tab.
 */
function kantan_render_ai_crawlers_tab($tab, $days) {
    if ($tab !== 'ai-crawlers') {
        return;
    }

    $days = max(1, intval($days));

    $totals       = kantan_get_ai_crawler_totals($days);
    $crawler_rows = kantan_get_ai_crawler_breakdown($days);
    $top_pages    = kantan_get_top_crawled_pages($days, 10);

    // Upsell visibility: only when SEO isn't already installed.
    $show_seo_upsell = !defined('KANTAN_SEO_VERSION');
    // Promotional intensity: full everywhere except the wp.org build.
    $channel = defined('KANTAN_ANALYTICS_CHANNEL') ? KANTAN_ANALYTICS_CHANNEL : 'trykantan';
    $upsell_full = ($channel !== 'wporg');

    include KANTAN_ANALYTICS_PLUGIN_DIR . 'templates/ai-crawlers-tab.php';
}
add_action('kantan_analytics_render_tab', 'kantan_render_ai_crawlers_tab', 10, 2);

/**
 * GET /kantan/v1/crawlers?days=30
 * AI-crawler activity: headline totals + per-crawler breakdown (the same data the
 * AI Crawlers dashboard tab shows). Lets the agent answer "who is crawling my site,
 * how often, and is it live-fetch or training?".
 */
function kantan_crawlers_register_rest_routes() {
    register_rest_route('kantan/v1', '/crawlers', array(
        'methods'             => 'GET',
        'callback'            => 'kantan_rest_get_crawlers',
        'permission_callback' => 'kantan_rest_permission',
    ));
}
add_action('rest_api_init', 'kantan_crawlers_register_rest_routes');

function kantan_rest_get_crawlers($request) {
    $days = max(1, min(3650, intval($request->get_param('days') ?: 30)));

    $rows = array_map(function ($row) {
        return array(
            'crawler'   => $row->crawler,
            'type'      => $row->crawler_type, // 'crawl' = training, 'fetch' = live retrieval
            'hits'      => (int) $row->hits,
            'pages'     => (int) $row->pages,
            'last_seen' => $row->last_seen,
        );
    }, kantan_get_ai_crawler_breakdown($days));

    return rest_ensure_response(array(
        'days'     => $days,
        'totals'   => kantan_get_ai_crawler_totals($days),
        'crawlers' => $rows,
    ));
}
