<?php
/**
 * Conversions Tab
 *
 * Gives the conversion data Analytics already collects a proper home in the
 * dashboard (totals, by type, by source, recent), instead of only surfacing it
 * once the paid Kantan SEO plugin is installed.
 *
 * The tab also offers Kantan SEO as the upgrade — it adds a dollar value to
 * every conversion and attributes conversions to organic keywords and pages.
 * That upsell is shown only when SEO is NOT active, and its intensity is gated
 * by the distribution channel: restrained on the wp.org build, fuller on the
 * directly-distributed build (see KANTAN_ANALYTICS_CHANNEL).
 */

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

/**
 * Register the Conversions tab, inserted just before Settings in the Analytics
 * group. Priority 5 so it lands before companion-plugin (SEO) tabs.
 */
function kantan_register_conversions_tab($tabs) {
    $entry = array(
        'conversions' => array(
            'label' => __('Conversions', 'kantan-analytics'),
            'group' => __('Analytics', 'kantan-analytics'),
            'icon'  => '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></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_conversions_tab', 5);

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

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

    $total_conversions     = kantan_get_total_conversions($days);
    $conversion_summary    = kantan_get_conversion_summary($days);
    $conversions_by_source = kantan_get_conversions_by_source($days);
    $recent_conversions    = kantan_get_recent_conversions($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/conversions-tab.php';
}
add_action('kantan_analytics_render_tab', 'kantan_render_conversions_tab', 10, 2);
