<?php

/**
 * Recommended Next Actions Engine
 * Rule-based recommendations derived from analytics data — no AI needed
 */

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

/**
 * Get recommendations for a specific tab
 *
 * @param string $tab    Tab ID (overview, interactions, journeys)
 * @param int    $days   Date range in days
 * @return array Array of recommendation objects sorted by priority
 */
function kantan_get_recommendations($tab, $days = 30) {
    $fn = "kantan_recommendations_{$tab}";
    if (function_exists($fn)) {
        $recs = $fn($days);
        // Sort by priority: high first, then medium, then low
        $priority_order = ['high' => 0, 'medium' => 1, 'low' => 2];
        usort($recs, function ($a, $b) use ($priority_order) {
            return ($priority_order[$a['priority']] ?? 3) - ($priority_order[$b['priority']] ?? 3);
        });
        return $recs;
    }

    // Allow companion plugins to provide recommendations for their tabs
    return apply_filters('kantan_recommendations_' . $tab, [], $days);
}

/**
 * Overview tab recommendations
 */
function kantan_recommendations_overview($days) {
    $recs = [];

    $total_visits = kantan_get_total_visits($days);
    $bounce_rate = kantan_get_bounce_rate($days);
    $avg_duration = kantan_get_avg_duration($days);
    $traffic_sources = kantan_get_traffic_sources($days);
    $top_pages = kantan_get_top_pages($days, 5);
    $visits_by_day = kantan_get_visits_by_day($days);

    // — Not enough data yet
    if ($total_visits < 10) {
        $recs[] = [
            'priority' => 'medium',
            'title'    => __('Not enough data yet', 'kantan-analytics'),
            'action'   => __('Your site has fewer than 10 visits in this period. Focus on driving traffic — share your site on social media, submit to Google Search Console, and ensure your sitemap is indexed.', 'kantan-analytics'),
            /* translators: %d: number of visits */
            'metric'   => sprintf(_n('%d visit', '%d visits', $total_visits, 'kantan-analytics'), $total_visits),
        ];
        return $recs; // No point analyzing further
    }

    // — High bounce rate
    if ($bounce_rate > 70) {
        $worst_page = kantan_get_highest_bounce_page($days);
        /* translators: 1: page title, 2: bounce rate percentage */
        $page_hint = $worst_page ? ' ' . sprintf(__('Start with "%1$s" (%2$s%% bounce rate).', 'kantan-analytics'), $worst_page->page_title, $worst_page->bounce_rate) : '';
        $recs[] = [
            'priority' => 'high',
            'title'    => __('Reduce bounce rate', 'kantan-analytics'),
            /* translators: 1: bounce rate percentage, 2: optional sentence naming the worst page */
            'action'   => sprintf(__('Your bounce rate is %1$s%% — most visitors leave after one page. Add internal links, stronger CTAs, or related content to keep visitors exploring.%2$s', 'kantan-analytics'), $bounce_rate, $page_hint),
            /* translators: %s: bounce rate percentage */
            'metric'   => sprintf(__('%s%% bounce rate', 'kantan-analytics'), $bounce_rate),
        ];
    }

    // — Low average duration
    if ($avg_duration > 0 && $avg_duration < 30) {
        $recs[] = [
            'priority' => 'high',
            'title'    => __('Increase time on site', 'kantan-analytics'),
            /* translators: %s: average time on site, e.g. "25s" */
            'action'   => sprintf(__('Visitors spend an average of %s on your site. Consider adding more engaging content, videos, or interactive elements to hold attention longer.', 'kantan-analytics'), kantan_format_duration($avg_duration)),
            /* translators: %s: average time on site, e.g. "25s" */
            'metric'   => sprintf(__('%s avg', 'kantan-analytics'), kantan_format_duration($avg_duration)),
        ];
    }

    // — Traffic source over-reliance
    if ($total_visits >= 20) {
        foreach ($traffic_sources as $source) {
            $pct = round(($source->visits / $total_visits) * 100, 1);
            if ($pct > 80) {
                $source_name = ucfirst($source->traffic_source);
                $diversify_hints = [
                    'direct'   => __('Build organic search presence with content targeting relevant keywords, and share on social media.', 'kantan-analytics'),
                    'organic'  => __('Diversify with social media, email newsletters, or referral partnerships to reduce dependency on search rankings.', 'kantan-analytics'),
                    'social'   => __('Invest in SEO to build organic search traffic that compounds over time.', 'kantan-analytics'),
                    'referral' => __('Invest in SEO and build a direct audience through email or social channels.', 'kantan-analytics'),
                    'ai'       => __('AI assistants send most of your traffic — keep answer-engine content strong (clear Q&A, FAQ schema), but diversify into organic search and direct channels, since AI citations can shift fast.', 'kantan-analytics'),
                ];
                $hint = $diversify_hints[$source->traffic_source] ?? __('Explore additional traffic channels to reduce risk.', 'kantan-analytics');
                $recs[] = [
                    'priority' => 'medium',
                    'title'    => __('Diversify traffic sources', 'kantan-analytics'),
                    /* translators: 1: traffic share percentage, 2: traffic source name, 3: diversification hint sentence */
                    'action'   => sprintf(__('%1$s%% of your traffic comes from %2$s. %3$s', 'kantan-analytics'), $pct, $source_name, $hint),
                    'metric'   => $pct . '% ' . strtolower($source_name),
                ];
                break;
            }
        }
    }

    // — Declining traffic trend
    if (count($visits_by_day) >= 14) {
        $mid = intdiv(count($visits_by_day), 2);
        $first_half = array_slice($visits_by_day, 0, $mid);
        $second_half = array_slice($visits_by_day, $mid);
        $first_avg = array_sum(array_map(fn($v) => $v->visits, $first_half)) / count($first_half);
        $second_avg = array_sum(array_map(fn($v) => $v->visits, $second_half)) / count($second_half);

        if ($first_avg > 0 && $second_avg < $first_avg * 0.7) {
            $drop = round((1 - $second_avg / $first_avg) * 100);
            $recs[] = [
                'priority' => 'high',
                'title'    => __('Traffic is declining', 'kantan-analytics'),
                /* translators: %s: percentage drop in daily visits */
                'action'   => sprintf(__('Daily visits dropped ~%s%% in the second half of this period. Check for ranking losses in Search Console, verify no technical issues (slow load, broken pages), and consider publishing fresh content.', 'kantan-analytics'), $drop),
                /* translators: %s: percentage decline */
                'metric'   => sprintf(__('%s%% decline', 'kantan-analytics'), $drop),
            ];
        } elseif ($first_avg > 0 && $second_avg > $first_avg * 1.3) {
            $gain = round(($second_avg / $first_avg - 1) * 100);
            $recs[] = [
                'priority' => 'low',
                'title'    => __('Traffic is growing', 'kantan-analytics'),
                /* translators: %s: percentage increase in daily visits */
                'action'   => sprintf(__('Daily visits are up ~%s%%. Keep doing what\'s working — identify which pages or sources are driving the growth and double down.', 'kantan-analytics'), $gain),
                /* translators: %s: percentage growth */
                'metric'   => sprintf(__('%s%% growth', 'kantan-analytics'), $gain),
            ];
        }
    }

    // — No organic traffic
    $has_organic = false;
    foreach ($traffic_sources as $source) {
        if ($source->traffic_source === 'organic' && $source->visits > 0) {
            $has_organic = true;
        }
    }
    if (!$has_organic && $total_visits >= 20) {
        $recs[] = [
            'priority' => 'high',
            'title'    => __('No organic search traffic', 'kantan-analytics'),
            'action'   => __('You\'re getting zero visitors from search engines. Submit your sitemap to Google Search Console, ensure pages have unique title tags and meta descriptions, and start targeting keywords with blog content.', 'kantan-analytics'),
            'metric'   => __('0 organic visits', 'kantan-analytics'),
        ];
    }

    // — All good fallback
    if (empty($recs)) {
        $recs[] = [
            'priority' => 'low',
            'title'    => __('Looking good', 'kantan-analytics'),
            'action'   => __('No issues detected. Keep monitoring your metrics and focus on creating quality content that serves your visitors.', 'kantan-analytics'),
            'metric'   => '',
        ];
    }

    return $recs;
}

/**
 * Interactions tab recommendations
 */
function kantan_recommendations_interactions($days) {
    $recs = [];

    $total_clicks = kantan_get_total_clicks($days);
    $click_regions = kantan_get_click_regions($days);
    $top_clicked = kantan_get_top_clicked_elements($days, 10);
    $avg_scroll = kantan_get_avg_scroll_depth($days);
    $scroll_dist = kantan_get_scroll_distribution('', $days);
    $total_visits = kantan_get_total_visits($days);

    // — No click data
    if ($total_clicks === 0) {
        $recs[] = [
            'priority' => 'medium',
            'title'    => __('No click data yet', 'kantan-analytics'),
            'action'   => __('Click tracking is active but no clicks have been recorded. This is normal for new sites — data will appear as visitors interact with your pages.', 'kantan-analytics'),
            'metric'   => __('0 clicks', 'kantan-analytics'),
        ];
        return $recs;
    }

    // — Low scroll depth
    if ($avg_scroll > 0 && $avg_scroll < 40) {
        $recs[] = [
            'priority' => 'high',
            'title'    => __('Visitors aren\'t scrolling', 'kantan-analytics'),
            /* translators: %s: average scroll depth percentage */
            'action'   => sprintf(__('Average scroll depth is only %s%%. Most visitors never see your below-the-fold content. Move important CTAs and key information higher on the page, or add visual hooks (images, headings) to encourage scrolling.', 'kantan-analytics'), $avg_scroll),
            /* translators: %s: average scroll depth percentage */
            'metric'   => sprintf(__('%s%% avg scroll', 'kantan-analytics'), $avg_scroll),
        ];
    }

    // — Most visitors abandon before halfway (scroll distribution)
    if ($scroll_dist && $scroll_dist->total > 10) {
        $top_half_pct = round((($scroll_dist->depth_25 + $scroll_dist->depth_50) / $scroll_dist->total) * 100);
        if ($top_half_pct > 75) {
            $recs[] = [
                'priority' => 'medium',
                'title'    => __('Content below the fold is ignored', 'kantan-analytics'),
                /* translators: %s: percentage of visitors who stop scrolling early */
                'action'   => sprintf(__('%s%% of visitors stop scrolling before reaching the bottom half of your pages. Consider shortening pages, adding anchor links, or placing your most important content and CTAs in the top half.', 'kantan-analytics'), $top_half_pct),
                /* translators: %s: percentage of visitors who stop scrolling early */
                'metric'   => sprintf(__('%s%% stop early', 'kantan-analytics'), $top_half_pct),
            ];
        }
    }

    // — Clicks on non-interactive elements
    $non_interactive_tags = ['div', 'span', 'p', 'img', 'section', 'li', 'td', 'h1', 'h2', 'h3', 'h4', 'label'];
    $dead_clicks = [];
    foreach ($top_clicked as $el) {
        if (in_array(strtolower($el->element_tag), $non_interactive_tags) && $el->clicks >= 3) {
            $dead_clicks[] = $el;
        }
    }
    if (!empty($dead_clicks)) {
        $element = $dead_clicks[0];
        $text_preview = mb_strlen($element->element_text) > 40 ? mb_substr($element->element_text, 0, 40) . '...' : $element->element_text;
        $recs[] = [
            'priority' => 'medium',
            'title'    => __('Visitors are clicking non-interactive elements', 'kantan-analytics'),
            /* translators: 1: HTML tag name, 2: element text preview, 3: number of clicks */
            'action'   => sprintf(__('The <%1$s> element "%2$s" was clicked %3$d times but isn\'t a link or button. Visitors expect it to be interactive — consider making it clickable or adding a link.', 'kantan-analytics'), $element->element_tag, $text_preview, $element->clicks),
            /* translators: %d: number of dead clicks */
            'metric'   => sprintf(_n('%d dead click', '%d dead clicks', $element->clicks, 'kantan-analytics'), $element->clicks),
        ];
    }

    // — Bottom of page gets no clicks
    $bottom_clicks = ($click_regions[7] ?? 0) + ($click_regions[8] ?? 0) + ($click_regions[9] ?? 0);
    if ($total_clicks > 20 && $bottom_clicks === 0) {
        $recs[] = [
            'priority' => 'low',
            'title'    => __('No clicks at page bottom', 'kantan-analytics'),
            'action'   => __('The bottom third of your pages gets zero clicks. If you have CTAs in the footer, consider adding them higher on the page where visitors actually engage.', 'kantan-analytics'),
            'metric'   => __('0 bottom clicks', 'kantan-analytics'),
        ];
    }

    // — Low click-to-visit ratio
    if ($total_visits > 20 && $total_clicks > 0) {
        $clicks_per_visit = round($total_clicks / $total_visits, 1);
        if ($clicks_per_visit < 1) {
            $recs[] = [
                'priority' => 'medium',
                'title'    => __('Low engagement per visit', 'kantan-analytics'),
                /* translators: %s: average clicks per session */
                'action'   => sprintf(__('Visitors average only %s clicks per session. Add clearer calls-to-action, navigation aids, or interactive elements to encourage engagement.', 'kantan-analytics'), $clicks_per_visit),
                /* translators: %s: clicks per visit */
                'metric'   => sprintf(__('%s clicks/visit', 'kantan-analytics'), $clicks_per_visit),
            ];
        }
    }

    if (empty($recs)) {
        $recs[] = [
            'priority' => 'low',
            'title'    => __('Interactions look healthy', 'kantan-analytics'),
            'action'   => __('Visitors are clicking and scrolling through your content. Keep an eye on dead clicks and scroll depth as you add new pages.', 'kantan-analytics'),
            'metric'   => '',
        ];
    }

    return $recs;
}

/**
 * Journeys tab recommendations
 */
function kantan_recommendations_journeys($days) {
    $recs = [];

    $journeys = kantan_get_session_journeys($days, 20);
    $entry_pages = kantan_get_entry_pages($days, 10);
    $exit_pages = kantan_get_exit_pages($days, 10);
    $total_visits = kantan_get_total_visits($days);

    // — No journey data
    if (empty($journeys)) {
        $recs[] = [
            'priority' => 'medium',
            'title'    => __('No journey data yet', 'kantan-analytics'),
            'action'   => __('Journey tracking is active but no multi-page sessions have been recorded yet. Data will appear as visitors browse multiple pages.', 'kantan-analytics'),
            'metric'   => __('0 journeys', 'kantan-analytics'),
        ];
        return $recs;
    }

    // — Average pages per session
    $total_page_count = 0;
    $journey_count = count($journeys);
    foreach ($journeys as $j) {
        $total_page_count += $j->page_count;
    }
    $avg_pages = $journey_count > 0 ? round($total_page_count / $journey_count, 1) : 0;

    if ($avg_pages <= 1.2) {
        $recs[] = [
            'priority' => 'high',
            'title'    => __('Most sessions are single-page', 'kantan-analytics'),
            /* translators: %s: average pages viewed per session */
            'action'   => sprintf(__('Visitors view an average of %s pages per session. Add related content links, "Read next" sections, or prominent navigation to encourage exploration.', 'kantan-analytics'), $avg_pages),
            /* translators: %s: average pages per session */
            'metric'   => sprintf(__('%s pages/session', 'kantan-analytics'), $avg_pages),
        ];
    }

    // — Single entry page dominance
    if (count($entry_pages) >= 2 && $total_visits > 10) {
        $top_entry = $entry_pages[0];
        $top_pct = round(($top_entry->entries / $total_visits) * 100);
        if ($top_pct > 85) {
            $path = wp_parse_url($top_entry->page_url, PHP_URL_PATH) ?: '/';
            $recs[] = [
                'priority' => 'medium',
                'title'    => __('Almost all traffic lands on one page', 'kantan-analytics'),
                /* translators: 1: percentage of sessions, 2: page path */
                'action'   => sprintf(__('%1$s%% of sessions start on "%2$s". Create additional landing pages targeting different keywords or topics to capture more diverse search traffic.', 'kantan-analytics'), $top_pct, $path),
                /* translators: 1: percentage of sessions, 2: page path */
                'metric'   => sprintf(__('%1$s%% on %2$s', 'kantan-analytics'), $top_pct, $path),
            ];
        }
    }

    // — High exit rate on a non-homepage
    if (!empty($exit_pages) && $total_visits > 10) {
        foreach ($exit_pages as $exit) {
            $path = wp_parse_url($exit->page_url, PHP_URL_PATH) ?: '/';
            if ($path === '/') continue; // Homepage exits are normal
            $exit_pct = round(($exit->exits / $total_visits) * 100);
            if ($exit_pct > 30) {
                $recs[] = [
                    'priority' => 'medium',
                    /* translators: %s: page path */
                    'title'    => sprintf(__('High exit rate on "%s"', 'kantan-analytics'), $path),
                    /* translators: %s: percentage of visitors who exit from this page */
                    'action'   => sprintf(__('%s%% of visitors leave your site from this page. Add a call-to-action, related content links, or a clear next step to keep visitors engaged.', 'kantan-analytics'), $exit_pct),
                    /* translators: %s: exit percentage */
                    'metric'   => sprintf(__('%s%% exit here', 'kantan-analytics'), $exit_pct),
                ];
                break; // Only show the worst one
            }
        }
    }

    // — Entry pages with no onward journeys (dead ends)
    if (!empty($entry_pages) && $total_visits > 10) {
        $transitions = kantan_get_page_transitions($days, 50);
        $pages_with_transitions = [];
        foreach ($transitions as $t) {
            $pages_with_transitions[$t->from_page] = true;
        }

        foreach ($entry_pages as $entry) {
            if ($entry->entries < 3) continue;
            if (!isset($pages_with_transitions[$entry->page_url])) {
                $path = wp_parse_url($entry->page_url, PHP_URL_PATH) ?: '/';
                $recs[] = [
                    'priority' => 'high',
                    /* translators: %s: page path */
                    'title'    => sprintf(__('"%s" is a dead end', 'kantan-analytics'), $path),
                    /* translators: %d: number of entries to this page */
                    'action'   => sprintf(_n('This page gets %d entry but no one navigates onward. Add internal links or a clear next step to guide visitors deeper into your site.', 'This page gets %d entries but no one navigates onward. Add internal links or a clear next step to guide visitors deeper into your site.', $entry->entries, 'kantan-analytics'), $entry->entries),
                    /* translators: %d: number of entries to this page */
                    'metric'   => sprintf(_n('%d entry, 0 onward', '%d entries, 0 onward', $entry->entries, 'kantan-analytics'), $entry->entries),
                ];
                break; // Only show the worst one
            }
        }
    }

    if (empty($recs)) {
        $recs[] = [
            'priority' => 'low',
            'title'    => __('Journeys look healthy', 'kantan-analytics'),
            'action'   => __('Visitors are navigating through multiple pages. Keep building internal links and content paths that guide visitors toward your goals.', 'kantan-analytics'),
            'metric'   => '',
        ];
    }

    return $recs;
}

/* ========================================
   HELPER QUERIES
   ======================================== */

/**
 * Get the page with the highest bounce rate (minimum 5 visits)
 */
function kantan_get_highest_bounce_page($days = 30) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'kantan_analytics';
    $date = gmdate('Y-m-d H:i:s', strtotime("-$days days"));

    return $wpdb->get_row($wpdb->prepare(
        "SELECT page_url, page_title,
            COUNT(DISTINCT session_id) as visits,
            ROUND(SUM(is_bounce) / COUNT(DISTINCT session_id) * 100, 1) as bounce_rate
        FROM $table_name
        WHERE visit_date >= %s
        GROUP BY page_url
        HAVING visits >= 5
        ORDER BY bounce_rate DESC
        LIMIT 1",
        $date
    ));
}
