<?php
/**
 * Recommendations Data - Manage recommendation requests and outcomes
 */

try {
    $db = MongoDBConnection::getInstance()->getDatabase();
    
    // Get pagination parameters
    $page_num = (int)($_GET['page_num'] ?? 1);
    $items_per_page = 25;
    $skip = ($page_num - 1) * $items_per_page;
    
    // Get filter parameters
    $tenant_filter = $_GET['tenant'] ?? '';
    $status_filter = $_GET['status'] ?? '';
    $date_range = $_GET['range'] ?? '7';
    
    // Date range filter
    $start_date = new MongoDB\BSON\UTCDateTime((time() - ((int)$date_range * 24 * 60 * 60)) * 1000);
    $end_date = new MongoDB\BSON\UTCDateTime(time() * 1000);
    
    // Build filter
    $filter = [
        'req_ts' => ['$gte' => $start_date, '$lte' => $end_date]
    ];
    
    if (!empty($tenant_filter)) {
        $filter['tenant_id'] = $tenant_filter;
    }
    
    if (!empty($status_filter)) {
        $filter['status'] = $status_filter;
    }
    
    // Get total count for pagination
    $total_recommendations = $db->reco_requests->countDocuments($filter);
    $total_pages = ceil($total_recommendations / $items_per_page);
    
    // Get recommendations with pagination
    $recommendations_cursor = $db->reco_requests->find($filter, [
        'sort' => ['req_ts' => -1],
        'skip' => $skip,
        'limit' => $items_per_page
    ]);
    
    $recommendations = [];
    foreach ($recommendations_cursor as $reco) {
        $recommendation_data = [
            'id' => (string)$reco['_id'],
            'request_id' => $reco['request_id'] ?? (string)$reco['_id'],
            'tenant_id' => $reco['tenant_id'],
            'app_id' => $reco['app_id'] ?? '',
            'user_id' => $reco['user_id'] ?? '',
            'req_ts' => $reco['req_ts'],
            'response_time_ms' => $reco['response_time_ms'] ?? 0,
            'num_results' => $reco['num_results'] ?? 0,
            'status' => $reco['status'] ?? 'success',
            'error_message' => $reco['error_message'] ?? null,
            'clicks' => $reco['clicks'] ?? 0,
            'impressions' => $reco['impressions'] ?? 0,
            'ctr' => $reco['ctr'] ?? 0
        ];
        
        $recommendations[] = $recommendation_data;
    }
    
    // Get recommendation statistics
    $reco_stats = [
        'total_requests' => $total_recommendations,
        'successful' => $db->reco_requests->countDocuments(array_merge($filter, ['status' => 'success'])),
        'failed' => $db->reco_requests->countDocuments(array_merge($filter, ['status' => 'failed'])),
        'avg_response_time' => 0,
        'avg_ctr' => 0,
        'total_clicks' => 0,
        'total_impressions' => 0
    ];
    
    // Calculate averages
    try {
        $avg_pipeline = [
            ['$match' => $filter],
            ['$group' => [
                '_id' => null,
                'avg_response_time' => ['$avg' => '$response_time_ms'],
                'avg_ctr' => ['$avg' => '$ctr'],
                'total_clicks' => ['$sum' => '$clicks'],
                'total_impressions' => ['$sum' => '$impressions']
            ]]
        ];
        
        $avg_result = $db->reco_requests->aggregate($avg_pipeline)->toArray();
        if (!empty($avg_result)) {
            $reco_stats['avg_response_time'] = round($avg_result[0]['avg_response_time'] ?? 0, 2);
            $reco_stats['avg_ctr'] = round($avg_result[0]['avg_ctr'] ?? 0, 4);
            $reco_stats['total_clicks'] = $avg_result[0]['total_clicks'] ?? 0;
            $reco_stats['total_impressions'] = $avg_result[0]['total_impressions'] ?? 0;
        }
    } catch (Exception $e) {
        error_log("Error calculating recommendation averages: " . $e->getMessage());
    }
    
    // Performance trends
    $performance_trends = [];
    try {
        $trends_pipeline = [
            ['$match' => $filter],
            ['$group' => [
                '_id' => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$req_ts']],
                'requests' => ['$sum' => 1],
                'avg_response_time' => ['$avg' => '$response_time_ms'],
                'avg_ctr' => ['$avg' => '$ctr'],
                'errors' => ['$sum' => ['$cond' => [['$eq' => ['$status', 'failed']], 1, 0]]]
            ]],
            ['$sort' => ['_id' => 1]]
        ];
        
        $trends_result = $db->reco_requests->aggregate($trends_pipeline)->toArray();
        foreach ($trends_result as $trend) {
            $performance_trends[] = [
                'date' => $trend['_id'],
                'requests' => $trend['requests'],
                'avg_response_time' => round($trend['avg_response_time'], 2),
                'avg_ctr' => round($trend['avg_ctr'], 4),
                'errors' => $trend['errors'],
                'success_rate' => round((($trend['requests'] - $trend['errors']) / $trend['requests']) * 100, 2)
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting performance trends: " . $e->getMessage());
    }
    
    // Top performing recommendations
    $top_recommendations = [];
    try {
        $top_pipeline = [
            ['$match' => array_merge($filter, ['status' => 'success'])],
            ['$sort' => ['ctr' => -1]],
            ['$limit' => 10],
            ['$project' => [
                'request_id' => 1,
                'tenant_id' => 1,
                'user_id' => 1,
                'req_ts' => 1,
                'ctr' => 1,
                'clicks' => 1,
                'impressions' => 1,
                'num_results' => 1
            ]]
        ];
        
        $top_result = $db->reco_requests->aggregate($top_pipeline)->toArray();
        foreach ($top_result as $top) {
            $top_recommendations[] = [
                'request_id' => $top['request_id'] ?? (string)$top['_id'],
                'tenant_id' => $top['tenant_id'],
                'user_id' => $top['user_id'] ?? 'anonymous',
                'req_ts' => $top['req_ts'],
                'ctr' => round($top['ctr'] ?? 0, 4),
                'clicks' => $top['clicks'] ?? 0,
                'impressions' => $top['impressions'] ?? 0,
                'num_results' => $top['num_results'] ?? 0
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting top recommendations: " . $e->getMessage());
    }
    
    // Recent failed requests
    $failed_requests = [];
    try {
        $failed_cursor = $db->reco_requests->find(
            array_merge($filter, ['status' => 'failed']),
            [
                'sort' => ['req_ts' => -1],
                'limit' => 5,
                'projection' => [
                    'request_id' => 1,
                    'tenant_id' => 1,
                    'app_id' => 1,
                    'req_ts' => 1,
                    'error_message' => 1
                ]
            ]
        );
        
        foreach ($failed_cursor as $failed) {
            $failed_requests[] = [
                'request_id' => $failed['request_id'] ?? (string)$failed['_id'],
                'tenant_id' => $failed['tenant_id'],
                'app_id' => $failed['app_id'] ?? '',
                'req_ts' => $failed['req_ts'],
                'error_message' => $failed['error_message'] ?? 'Unknown error'
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting failed requests: " . $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("Recommendations data error: " . $e->getMessage());
    
    // Fallback data
    $recommendations = [];
    $reco_stats = [
        'total_requests' => 0,
        'successful' => 0,
        'failed' => 0,
        'avg_response_time' => 0,
        'avg_ctr' => 0,
        'total_clicks' => 0,
        'total_impressions' => 0
    ];
    $performance_trends = [];
    $top_recommendations = [];
    $failed_requests = [];
    $tenants_list = [];
    $total_pages = 1;
    $error_message = "Failed to load recommendations data: " . $e->getMessage();
}

?>
