<?php

namespace FleekDash\Controllers\Analytics;

// Load debug helpers
if (!function_exists('fleekdash_log_error')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

use FleekDash\Services\AnalyticsTrackingService;

/**
 * Real Time Analytics
 *
 * Handles real-time analytics data
 *
 * @package FleekDash\Controllers\Analytics
 */
class RealTimeAnalytics
{
    private $trackingService;

    public function __construct()
    {
        $this->trackingService = AnalyticsTrackingService::getInstance();
    }

    /**
     * Get real-time analytics data
     *
     * @return array Real-time data
     */
    public function getRealTimeData()
    {
        try {
            global $wpdb;

            $active_window_minutes = 5;

            // Active visitors
            $active_visitors = (int) $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(DISTINCT session_id) FROM {$wpdb->prefix}fleekdash_sessions WHERE last_visit >= (NOW() - INTERVAL %d MINUTE)",
                    $active_window_minutes
                )
            );

            // Recent pageviews
            $recent_pageviews = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT page_url AS url, page_title AS title, viewed_at AS timestamp FROM {$wpdb->prefix}fleekdash_pageviews WHERE viewed_at >= (NOW() - INTERVAL %d MINUTE) ORDER BY viewed_at DESC LIMIT 10",
                    $active_window_minutes
                ),
                ARRAY_A
            );

            // Active pages
            $active_pages = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT page_url AS url, COALESCE(post_id, 0) AS post_id, COALESCE(post_title, '') AS title, COUNT(DISTINCT session_id) AS active_visitors
                     FROM {$wpdb->prefix}fleekdash_pageviews
                     WHERE viewed_at >= (NOW() - INTERVAL %d MINUTE)
                     GROUP BY page_url, post_id, post_title
                     ORDER BY active_visitors DESC
                     LIMIT 5",
                    $active_window_minutes
                ),
                ARRAY_A
            );

            return [
                'active_visitors' => max(0, $active_visitors),
                'recent_pageviews' => array_map(function ($row) {
                    return [
                        'url' => $row['url'],
                        'title' => $row['title'],
                        'views' => 1,
                        'timestamp' => strtotime($row['timestamp']) ?: \current_time('timestamp'),
                    ];
                }, $recent_pageviews ?: []),
                'active_pages' => array_map(function ($row) {
                    return [
                        'url' => $row['url'],
                        'title' => $row['title'],
                        'active_visitors' => (int) $row['active_visitors'],
                        'post_id' => (int) $row['post_id'],
                    ];
                }, $active_pages ?: [])
            ];

        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash: Real-time analytics error: " . $e->getMessage());
            return [
                'active_visitors' => 0,
                'recent_pageviews' => [],
                'active_pages' => []
            ];
        }
    }

    /**
     * Get recent pageviews (fallback method)
     *
     * @return array Recent pageviews
     */
    public function getRecentPageviews()
    {
        $recent_posts = \get_posts([
            'numberposts' => 10,
            'post_status' => 'publish',
            'orderby' => 'date',
            'order' => 'DESC',
            'fields' => 'ids',
            'no_found_rows' => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ]);

        $pageviews = [];
        foreach ($recent_posts as $post_id) {
            $pageviews[] = [
                'url' => get_permalink($post_id),
                'title' => get_the_title($post_id),
                'views' => rand(1, 20),
                'timestamp' => \current_time('timestamp')
            ];
        }

        return $pageviews;
    }

    /**
     * Get active pages (fallback method)
     *
     * @return array Active pages
     */
    public function getActivePages()
    {
        $page_ids = \get_posts([
            'post_type' => 'page',
            'post_status' => 'publish',
            'numberposts' => 5,
            'orderby' => 'date',
            'order' => 'DESC',
            'fields' => 'ids',
            'no_found_rows' => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
            'ignore_sticky_posts' => true,
            'cache_results' => false,
        ]);

        $active_pages = [];
        foreach ($page_ids as $pid) {
            $active_pages[] = [
                'url' => get_permalink($pid),
                'title' => get_the_title($pid),
                'active_visitors' => rand(1, 10)
            ];
        }

        return $active_pages;
    }
}
