<?php
/**
 * Dashboard Data - Fetch statistics and metrics from MongoDB
 */

try {
    $db = MongoDBConnection::getInstance()->getDatabase();
    
    // Get basic counts
    $stats = [
        'tenants' => get_collection_count('tenants', ['status' => 'active']),
        'total_tenants' => get_collection_count('tenants'),
        'apps' => get_collection_count('apps', ['status' => 'active']),
        'total_apps' => get_collection_count('apps'),
        'items' => get_collection_count('items'),
        'interactions_today' => 0,
        'recommendations_today' => 0
    ];
    
    // Get interactions count for today
    $today_start = new MongoDB\BSON\UTCDateTime(strtotime('today') * 1000);
    $stats['interactions_today'] = get_collection_count('interactions', [
        'ts' => ['$gte' => $today_start]
    ]);
    
    // Get recommendations count for today
    $stats['recommendations_today'] = get_collection_count('reco_requests', [
        'req_ts' => ['$gte' => $today_start]
    ]);
    
    // Get adapter distribution
    $adapter_stats = get_adapter_stats();
    
    // Get recent activity
    $recent_activities = get_recent_activity(5);
    
    // Get performance metrics for charts
    $performance_metrics = get_performance_metrics(7);
    
    // Get top tenants by activity
    $top_tenants = [];
    try {
        $pipeline = [
            [
                '$lookup' => [
                    'from' => 'interactions',
                    'localField' => 'tenant_id',
                    'foreignField' => 'tenant_id',
                    'as' => 'interactions'
                ]
            ],
            [
                '$addFields' => [
                    'interaction_count' => ['$size' => '$interactions']
                ]
            ],
            [
                '$sort' => ['interaction_count' => -1]
            ],
            [
                '$limit' => 5
            ],
            [
                '$project' => [
                    'name' => 1,
                    'tenant_id' => 1,
                    'status' => 1,
                    'interaction_count' => 1,
                    'created_at' => 1
                ]
            ]
        ];
        
        $top_tenants = $db->tenants->aggregate($pipeline)->toArray();
    } catch (Exception $e) {
        error_log("Error getting top tenants: " . $e->getMessage());
    }
    
    // Get recent errors or warnings
    $recent_issues = [];
    try {
        // Check for failed recommendation requests
        $failed_requests = $db->reco_requests->find(
            ['status' => 'failed'],
            [
                'sort' => ['req_ts' => -1],
                'limit' => 3,
                'projection' => ['tenant_id' => 1, 'app_id' => 1, 'error_message' => 1, 'req_ts' => 1]
            ]
        )->toArray();
        
        foreach ($failed_requests as $request) {
            $recent_issues[] = [
                'type' => 'error',
                'message' => 'Failed recommendation request for tenant ' . $request['tenant_id'],
                'details' => $request['error_message'] ?? 'Unknown error',
                'timestamp' => $request['req_ts']
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting recent issues: " . $e->getMessage());
    }
    
    // Calculate growth metrics (compare with previous period)
    $growth_metrics = [];
    try {
        $yesterday_start = new MongoDB\BSON\UTCDateTime(strtotime('yesterday') * 1000);
        $yesterday_end = new MongoDB\BSON\UTCDateTime(strtotime('today') * 1000);
        
        $yesterday_interactions = get_collection_count('interactions', [
            'ts' => [
                '$gte' => $yesterday_start,
                '$lt' => $yesterday_end
            ]
        ]);
        
        if ($yesterday_interactions > 0) {
            $growth_metrics['interactions'] = round((($stats['interactions_today'] - $yesterday_interactions) / $yesterday_interactions) * 100, 1);
        } else {
            $growth_metrics['interactions'] = 0;
        }
        
    } catch (Exception $e) {
        error_log("Error calculating growth metrics: " . $e->getMessage());
        $growth_metrics['interactions'] = 0;
    }
    
    // Get database statistics
    $db_stats = [];
    try {
        $stats_result = $db->command(['dbStats' => 1])->toArray();
        if (!empty($stats_result)) {
            $db_stats = [
                'collections' => $stats_result[0]['collections'] ?? 0,
                'dataSize' => format_bytes($stats_result[0]['dataSize'] ?? 0),
                'storageSize' => format_bytes($stats_result[0]['storageSize'] ?? 0),
                'indexes' => $stats_result[0]['indexes'] ?? 0
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting database stats: " . $e->getMessage());
    }
    
    // Get system health indicators
    $system_health = [
        'database_connection' => true,
        'collections_accessible' => true,
        'recent_errors' => count($recent_issues),
        'status' => count($recent_issues) == 0 ? 'healthy' : 'warning'
    ];
    
    // Prepare chart data for frontend
    $chart_data = [
        'adapter_distribution' => [
            'labels' => array_keys($adapter_stats),
            'data' => array_values($adapter_stats)
        ],
        'interactions_trend' => [],
        'performance_trend' => []
    ];
    
    // Format performance metrics for charts
    foreach ($performance_metrics as $date => $metrics) {
        $chart_data['interactions_trend'][] = [
            'date' => $date,
            'views' => $metrics['view'] ?? 0,
            'plays' => $metrics['play'] ?? 0,
            'purchases' => $metrics['purchase'] ?? 0
        ];
    }

} catch (Exception $e) {
    error_log("Dashboard data error: " . $e->getMessage());
    
    // Fallback data in case of errors
    $stats = [
        'tenants' => 0,
        'total_tenants' => 0,
        'apps' => 0,
        'total_apps' => 0,
        'items' => 0,
        'interactions_today' => 0,
        'recommendations_today' => 0
    ];
    
    $adapter_stats = [];
    $recent_activities = [];
    $performance_metrics = [];
    $top_tenants = [];
    $recent_issues = [];
    $growth_metrics = ['interactions' => 0];
    $db_stats = [];
    $system_health = ['status' => 'error'];
    $chart_data = ['adapter_distribution' => ['labels' => [], 'data' => []]];
}

?>
