<?php

/**
 * Admin Dashboard
 * Adds admin menu and displays analytics dashboard
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/* Add admin menu item */
function kantan_analytics_menu() {
    $menu_title = is_plugin_active( 'kantan-seo/kantan-seo.php' ) ? 'Kantan' : __('Analytics', 'kantan-analytics');
    add_menu_page(
        'Kantan Analytics',              // Page title
        $menu_title,                      // Menu title
        apply_filters('kantan_dashboard_capability', 'manage_options'), // Capability (demo lowers to a view-only cap)
        'kantan-analytics',               // Menu slug
        'kantan_analytics_dashboard_page', // Callback function
        'dashicons-chart-line',           // Icon
        26                                // Position
    );
}
add_action('admin_menu', 'kantan_analytics_menu');

/* Dashboard page callback */
function kantan_analytics_dashboard_page() {
    // Get analytics data
    $days = isset($_GET['days']) ? intval($_GET['days']) : 30;
    $total_visits = kantan_get_total_visits($days);
    $avg_duration = kantan_get_avg_duration($days);
    $bounce_rate = kantan_get_bounce_rate($days);
    $traffic_sources = kantan_get_traffic_sources($days);
    $top_referrers = kantan_get_top_referrer_domains($days);
    // Total across ALL referrers, so the block can offer to show what its
    // top-10 list is holding back.
    $referrer_total = kantan_get_referrer_domain_count($days);
    // Suspected-bot sessions excluded from the metrics above (0 when the filter is off).
    $bot_filtered_count = kantan_bot_filter_enabled() ? kantan_get_bot_session_count($days) : 0;
    $country_breakdown = function_exists('kantan_get_country_breakdown') ? kantan_get_country_breakdown($days, 8) : array();
    $visits_by_day = kantan_get_visits_by_day($days);
    $top_pages = kantan_get_top_pages($days);

    // Calculate organic vs search, and AI-assistant referrals
    $organic_count = 0;
    $search_count = 0;
    $ai_count = 0;
    foreach ($traffic_sources as $source) {
        if ($source->traffic_source === 'organic') {
            $organic_count = $source->visits;
        } elseif ($source->traffic_source === 'ai') {
            $ai_count = $source->visits;
        }
    }
    $search_count = $total_visits - $organic_count;

    // Per-assistant split of the AI bucket (ChatGPT vs Gemini vs …).
    $ai_breakdown = function_exists('kantan_get_ai_assistant_breakdown') ? kantan_get_ai_assistant_breakdown($days) : array();

    // Click tracking data
    $click_regions = kantan_get_click_regions($days);
    $total_clicks = kantan_get_total_clicks($days);
    $top_clicked_elements = kantan_get_top_clicked_elements($days, 5);
    $pages_with_clicks = kantan_get_pages_with_clicks($days, 10);

    // Journey / visitor data (only load when on journeys tab)
    $current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'overview';
    $visitor_profiles = ($current_tab === 'journeys') ? kantan_get_visitor_profiles($days, 20) : array();
    $page_transitions = ($current_tab === 'journeys') ? kantan_get_page_transitions($days, 10) : array();
    $entry_pages = ($current_tab === 'journeys') ? kantan_get_entry_pages($days, 5) : array();
    $exit_pages = ($current_tab === 'journeys') ? kantan_get_exit_pages($days, 5) : array();

    // Scroll depth data
    $avg_scroll_depth = kantan_get_avg_scroll_depth($days);
    $scroll_distribution = kantan_get_scroll_distribution('', $days);
    $scroll_by_page = kantan_get_scroll_depth_by_page($days, 12);

    // Sparkline data for overview stat cards
    $sparklines = ($current_tab === 'overview') ? kantan_get_sparkline_data($days) : array();

    // Recommendations for the current tab
    $recommendations = kantan_get_recommendations($current_tab, $days);

    // Include dashboard template
    include KANTAN_ANALYTICS_PLUGIN_DIR . 'templates/dashboard.php';
}

/* Enqueue admin styles */
function kantan_analytics_admin_assets($hook) {
    // Only load on our plugin page
    if ($hook !== 'toplevel_page_kantan-analytics') {
        return;
    }

    // Tailwind CSS — precompiled locally (no external CDN; see build/tailwind.config.js).
    wp_enqueue_style(
        'kantan-tailwind',
        KANTAN_ANALYTICS_PLUGIN_URL . 'assets/vendor/tailwind.min.css',
        array(),
        KANTAN_ANALYTICS_VERSION
    );

    // Dashboard styles (tooltip, etc.) — enqueued, not inlined.
    wp_enqueue_style(
        'kantan-analytics-admin',
        KANTAN_ANALYTICS_PLUGIN_URL . 'assets/css/admin.css',
        array('kantan-tailwind'),
        KANTAN_ANALYTICS_VERSION
    );

    // Chart.js — bundled locally (pinned 4.5.1).
    wp_enqueue_script(
        'chartjs',
        KANTAN_ANALYTICS_PLUGIN_URL . 'assets/vendor/chart.min.js',
        array(),
        '4.5.1',
        true
    );

    // Carrier handle for the dashboard's PHP-driven inline JS. It has no src of
    // its own — the template feeds each block to it via kantan_admin_inline_js()
    // (wp_add_inline_script) so no literal <script> tags are printed. Depends on
    // 'chartjs' so the bundle is defined before any inline block runs, and lives
    // in the footer so the DOM is fully parsed by execution time.
    wp_register_script('kantan-analytics-admin', false, array('chartjs'), KANTAN_ANALYTICS_VERSION, true);
    wp_enqueue_script('kantan-analytics-admin');
}
add_action('admin_enqueue_scripts', 'kantan_analytics_admin_assets');

/**
 * Attach a block of dashboard JavaScript to the carrier handle registered in
 * kantan_analytics_admin_assets(). Templates capture their script body with
 * ob_start()/ob_get_clean() and pass it here instead of emitting a <script>
 * tag, keeping all admin JS enqueued (a WordPress.org requirement). Blocks run
 * in call order, in the footer, after Chart.js and the full DOM are available.
 *
 * @param string $js Raw JavaScript (no surrounding <script> tags).
 */
function kantan_admin_inline_js($js) {
    if (trim((string) $js) === '') {
        return;
    }
    wp_add_inline_script('kantan-analytics-admin', $js);
}

/**
 * Output a help tooltip icon.
 *
 * @param string $text  Tooltip copy shown on hover.
 * @return string       HTML for the icon.
 */
function kantan_help_tip($text) {
    return '<span class="kantan-tip" data-tip="' . esc_attr($text) . '" aria-label="' . esc_attr($text) . '" role="tooltip">i</span>';
}

/**
 * Build a mailto: link to Kantan support, pre-filled with an issue template plus
 * environment diagnostics (versions, PHP, site) so reports arrive actionable.
 * Shared by both plugins' Settings tabs.
 *
 * @param string $plugin_label   e.g. 'Kantan SEO'
 * @param string $plugin_version e.g. '1.16.1'
 * @param array  $extra          Additional "Label" => "value" diagnostic lines.
 * @return string mailto: URL
 */
function kantan_support_mailto($plugin_label, $plugin_version, $extra = array()) {
    $diag = array(
        'Plugin'    => $plugin_label . ' ' . $plugin_version,
        'WordPress' => get_bloginfo('version'),
        'PHP'       => PHP_VERSION,
        'Site'      => home_url(),
    );
    foreach ($extra as $k => $v) {
        $diag[$k] = $v;
    }

    $lines = array();
    foreach ($diag as $k => $v) {
        $lines[] = $k . ': ' . $v;
    }

    $host    = wp_parse_url(home_url(), PHP_URL_HOST);
    $subject = $plugin_label . ' support — ' . $host;
    $body    = "Describe the issue — what you did, what you expected, and what happened:\n\n\n"
             . "—— Diagnostics (please keep) ——\n"
             . implode("\n", $lines) . "\n";

    return 'mailto:hello@trykantan.com?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);
}
