<?php
/**
 * Analytics Data - Generate analytics and insights from MongoDB
 */

// Include database configuration if not already included
if (!class_exists('MongoDBConnection')) {
    require_once __DIR__ . '/../config/database.php';
}

try {
    // Test MongoDB connection first
    $mongoConnection = MongoDBConnection::getInstance();
    $db = $mongoConnection->getDatabase();
    
    // Test the connection with a simple ping
    $db->command(['ping' => 1]);
    
    // Get date range parameters
    $date_range = $_GET['range'] ?? '7';
    $start_date = new MongoDB\BSON\UTCDateTime((time() - ((int)$date_range * 24 * 60 * 60)) * 1000);
    $end_date = new MongoDB\BSON\UTCDateTime(time() * 1000);
    
    // Get filter parameters
    $tenant_filter = $_GET['tenant'] ?? '';
    $adapter_filter = $_GET['adapter'] ?? '';
    
    // Base filter for analytics
    $base_filter = [
        'ts' => ['$gte' => $start_date, '$lte' => $end_date]
    ];
    
    if (!empty($tenant_filter)) {
        $base_filter['tenant_id'] = $tenant_filter;
    }
    
    // Overall analytics stats
    $analytics_stats = [
        'total_interactions' => 0,
        'unique_users' => 0,
        'total_recommendations' => 0,
        'avg_ctr' => 0,
        'top_events' => []
    ];
    
    // Get interaction statistics
    try {
        $analytics_stats['total_interactions'] = $db->interactions->countDocuments($base_filter);
        
        // Get unique users count
        $unique_users_pipeline = [
            ['$match' => $base_filter],
            ['$group' => ['_id' => '$user_id']],
            ['$count' => 'unique_users']
        ];
        $unique_users_result = $db->interactions->aggregate($unique_users_pipeline)->toArray();
        $analytics_stats['unique_users'] = $unique_users_result[0]['unique_users'] ?? 0;
        
        // Get event type distribution
        $events_pipeline = [
            ['$match' => $base_filter],
            ['$group' => ['_id' => '$event_type', 'count' => ['$sum' => 1]]],
            ['$sort' => ['count' => -1]],
            ['$limit' => 5]
        ];
        $events_result = $db->interactions->aggregate($events_pipeline)->toArray();
        foreach ($events_result as $event) {
            $analytics_stats['top_events'][] = [
                'event_type' => $event['_id'],
                'count' => $event['count']
            ];
        }
        
    } catch (Exception $e) {
        error_log("Error getting interaction analytics: " . $e->getMessage());
    }
    
    // Get recommendation statistics
    try {
        $reco_filter = [
            'req_ts' => ['$gte' => $start_date, '$lte' => $end_date]
        ];
        
        if (!empty($tenant_filter)) {
            $reco_filter['tenant_id'] = $tenant_filter;
        }
        
        $analytics_stats['total_recommendations'] = $db->reco_requests->countDocuments($reco_filter);
        
        // Calculate average CTR
        $ctr_pipeline = [
            ['$match' => $reco_filter],
            ['$group' => [
                '_id' => null,
                'avg_ctr' => ['$avg' => '$ctr'],
                'total_clicks' => ['$sum' => '$clicks'],
                'total_impressions' => ['$sum' => '$impressions']
            ]]
        ];
        $ctr_result = $db->reco_requests->aggregate($ctr_pipeline)->toArray();
        if (!empty($ctr_result)) {
            $analytics_stats['avg_ctr'] = round($ctr_result[0]['avg_ctr'] ?? 0, 3);
        }
        
    } catch (Exception $e) {
        error_log("Error getting recommendation analytics: " . $e->getMessage());
    }
    
    // Daily trends data for charts
    $daily_trends = [];
    try {
        $trends_pipeline = [
            ['$match' => $base_filter],
            ['$group' => [
                '_id' => [
                    'date' => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$ts']],
                    'event_type' => '$event_type'
                ],
                'count' => ['$sum' => 1]
            ]],
            ['$sort' => ['_id.date' => 1]]
        ];
        
        $trends_result = $db->interactions->aggregate($trends_pipeline)->toArray();
        foreach ($trends_result as $trend) {
            $date = $trend['_id']['date'];
            $event_type = $trend['_id']['event_type'];
            
            if (!isset($daily_trends[$date])) {
                $daily_trends[$date] = [];
            }
            $daily_trends[$date][$event_type] = $trend['count'];
        }
        
    } catch (Exception $e) {
        error_log("Error getting daily trends: " . $e->getMessage());
    }
    
    // Adapter performance
    $adapter_performance = [];
    if (empty($adapter_filter)) {
        try {
            $adapter_pipeline = [
                ['$lookup' => [
                    'from' => 'apps',
                    'localField' => 'tenant_id',
                    'foreignField' => 'tenant_id',
                    'as' => 'app'
                ]],
                ['$unwind' => '$app'],
                ['$match' => $base_filter],
                ['$group' => [
                    '_id' => '$app.adapter',
                    'interactions' => ['$sum' => 1],
                    'unique_users' => ['$addToSet' => '$user_id']
                ]],
                ['$project' => [
                    'adapter' => '$_id',
                    'interactions' => 1,
                    'unique_users' => ['$size' => '$unique_users']
                ]],
                ['$sort' => ['interactions' => -1]]
            ];
            
            $adapter_result = $db->interactions->aggregate($adapter_pipeline)->toArray();
            foreach ($adapter_result as $adapter) {
                $adapter_performance[] = [
                    'adapter' => $adapter['adapter'] ?? 'unknown',
                    'interactions' => $adapter['interactions'],
                    'unique_users' => $adapter['unique_users']
                ];
            }
            
        } catch (Exception $e) {
            error_log("Error getting adapter performance: " . $e->getMessage());
        }
    }
    
    // Top performing content
    $top_content = [];
    try {
        $content_pipeline = [
            ['$match' => $base_filter],
            ['$group' => [
                '_id' => '$item_id',
                'tenant_id' => ['$first' => '$tenant_id'],
                'interactions' => ['$sum' => 1],
                'unique_users' => ['$addToSet' => '$user_id']
            ]],
            ['$project' => [
                'item_id' => '$_id',
                'tenant_id' => 1,
                'interactions' => 1,
                'unique_users' => ['$size' => '$unique_users']
            ]],
            ['$sort' => ['interactions' => -1]],
            ['$limit' => 10]
        ];
        
        $content_result = $db->interactions->aggregate($content_pipeline)->toArray();
        foreach ($content_result as $content) {
            // Try to get item title
            $item_title = $content['item_id'];
            try {
                $item = $db->items->findOne([
                    'item_id' => $content['item_id'],
                    'tenant_id' => $content['tenant_id']
                ]);
                if ($item) {
                    $item_title = $item['title'] ?? $item['name'] ?? $content['item_id'];
                }
            } catch (Exception $e) {
                // Use item_id as fallback
            }
            
            $top_content[] = [
                'item_id' => $content['item_id'],
                'title' => $item_title,
                'tenant_id' => $content['tenant_id'],
                'interactions' => $content['interactions'],
                'unique_users' => $content['unique_users']
            ];
        }
        
    } catch (Exception $e) {
        error_log("Error getting top content: " . $e->getMessage());
    }
    
    // Get tenants list for filters
    $tenants_list = [];
    try {
        $tenants_cursor = $db->tenants->find([], [
            'sort' => ['name' => 1],
            'projection' => ['tenant_id' => 1, 'name' => 1]
        ]);
        
        foreach ($tenants_cursor as $tenant) {
            $tenants_list[] = [
                'tenant_id' => $tenant['tenant_id'],
                'name' => $tenant['name']
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting tenants list: " . $e->getMessage());
    }

} catch (Exception $e) {
    error_log("Analytics data error: " . $e->getMessage());
    
    // Fallback data
    $analytics_stats = [
        'total_interactions' => 0,
        'unique_users' => 0,
        'total_recommendations' => 0,
        'avg_ctr' => 0,
        'top_events' => []
    ];
    $daily_trends = [];
    $adapter_performance = [];
    $top_content = [];
    $tenants_list = [];
    
    // Set a user-friendly error message
    $error_message = "Unable to load analytics data. Please check your database connection and try again.";
    
    // Log the actual error for debugging
    error_log("Analytics error details: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
}

?>
