<?php
/**
 * Apps Data - Fetch and manage application information from MongoDB
 */

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 search and filter parameters
    $search = $_GET['search'] ?? '';
    $adapter_filter = $_GET['adapter'] ?? '';
    $tenant_filter = $_GET['tenant'] ?? '';
    $status_filter = $_GET['status'] ?? '';
    
    // Build filter
    $filter = [];
    if (!empty($search)) {
        $search_regex = new MongoDB\BSON\Regex(escape_mongo_regex($search), 'i');
        $filter['$or'] = [
            ['name' => $search_regex],
            ['app_id' => $search_regex],
            ['tenant_id' => $search_regex]
        ];
    }
    
    if (!empty($adapter_filter)) {
        $filter['adapter'] = $adapter_filter;
    }
    
    if (!empty($tenant_filter)) {
        $filter['tenant_id'] = $tenant_filter;
    }
    
    if (!empty($status_filter)) {
        $filter['status'] = $status_filter;
    }
    
    // Get total count for pagination
    $total_apps = $db->apps->countDocuments($filter);
    $total_pages = ceil($total_apps / $items_per_page);
    
    // Get apps with pagination
    $apps_cursor = $db->apps->find($filter, [
        'sort' => ['created_at' => -1],
        'skip' => $skip,
        'limit' => $items_per_page
    ]);
    
    $apps = [];
    foreach ($apps_cursor as $app) {
        $app_data = [
            'id' => (string)$app['_id'],
            'app_id' => $app['app_id'],
            'tenant_id' => $app['tenant_id'],
            'name' => $app['name'],
            'adapter' => $app['adapter'],
            'status' => $app['status'] ?? 'active',
            'created_at' => $app['created_at'],
            'updated_at' => $app['updated_at'] ?? null,
            'rpm_limit' => $app['rpm_limit'] ?? 1000,
            'items_count' => 0,
            'interactions_count' => 0
        ];
        
        // Get related counts for each app
        try {
            // Count items
            $app_data['items_count'] = $db->items->countDocuments([
                'tenant_id' => $app['tenant_id'],
                'app_id' => $app['app_id']
            ]);
            
            // Count recent interactions (last 30 days)
            $thirty_days_ago = new MongoDB\BSON\UTCDateTime((time() - (30 * 24 * 60 * 60)) * 1000);
            $app_data['interactions_count'] = $db->interactions->countDocuments([
                'tenant_id' => $app['tenant_id'],
                'app_id' => $app['app_id'],
                'ts' => ['$gte' => $thirty_days_ago]
            ]);
            
        } catch (Exception $e) {
            error_log("Error getting app stats for {$app['app_id']}: " . $e->getMessage());
        }
        
        $apps[] = $app_data;
    }
    
    // Get app statistics for summary
    $app_stats = [
        'total' => $total_apps,
        'active' => $db->apps->countDocuments(['status' => 'active']),
        'inactive' => $db->apps->countDocuments(['status' => 'inactive']),
        'ott' => $db->apps->countDocuments(['adapter' => 'ott']),
        'retail' => $db->apps->countDocuments(['adapter' => 'retail']),
        'pharma' => $db->apps->countDocuments(['adapter' => 'pharma']),
        'consulting' => $db->apps->countDocuments(['adapter' => 'consulting'])
    ];
    
    // Get recent app activity
    $recent_apps = [];
    try {
        $recent_cursor = $db->apps->find([], [
            'sort' => ['created_at' => -1],
            'limit' => 5,
            'projection' => ['app_id' => 1, 'name' => 1, 'adapter' => 1, 'tenant_id' => 1, 'status' => 1, 'created_at' => 1]
        ]);
        
        foreach ($recent_cursor as $app) {
            $recent_apps[] = [
                'app_id' => $app['app_id'],
                'name' => $app['name'],
                'adapter' => $app['adapter'],
                'tenant_id' => $app['tenant_id'],
                'status' => $app['status'],
                'created_at' => $app['created_at']
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting recent apps: " . $e->getMessage());
    }
    
    // Get list of tenants 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("Apps data error: " . $e->getMessage());
    
    // Fallback data
    $apps = [];
    $app_stats = ['total' => 0, 'active' => 0, 'inactive' => 0, 'ott' => 0, 'retail' => 0, 'pharma' => 0, 'consulting' => 0];
    $recent_apps = [];
    $tenants_list = [];
    $total_pages = 1;
    $error_message = "Failed to load app data: " . $e->getMessage();
}

?>
