<?php
/**
 * Items Data - Fetch and manage content items 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'] ?? '';
    $tenant_filter = $_GET['tenant'] ?? '';
    $app_filter = $_GET['app'] ?? '';
    $type_filter = $_GET['type'] ?? '';
    
    // Build filter
    $filter = [];
    if (!empty($search)) {
        $search_regex = new MongoDB\BSON\Regex(escape_mongo_regex($search), 'i');
        $filter['$or'] = [
            ['title' => $search_regex],
            ['item_id' => $search_regex],
            ['tenant_id' => $search_regex]
        ];
    }
    
    if (!empty($tenant_filter)) {
        $filter['tenant_id'] = $tenant_filter;
    }
    
    if (!empty($app_filter)) {
        $filter['app_id'] = $app_filter;
    }
    
    if (!empty($type_filter)) {
        $filter['type'] = $type_filter;
    }
    
    // Get total count for pagination
    $total_items = $db->items->countDocuments($filter);
    $total_pages = ceil($total_items / $items_per_page);
    
    // Get items with pagination
    $items_cursor = $db->items->find($filter, [
        'sort' => ['created_at' => -1],
        'skip' => $skip,
        'limit' => $items_per_page
    ]);
    
    $items = [];
    foreach ($items_cursor as $item) {
        $item_data = [
            'id' => (string)$item['_id'],
            'item_id' => $item['item_id'],
            'tenant_id' => $item['tenant_id'],
            'app_id' => $item['app_id'] ?? '',
            'title' => $item['title'] ?? $item['name'] ?? 'Untitled',
            'type' => $item['type'] ?? 'unknown',
            'created_at' => $item['created_at'],
            'updated_at' => $item['updated_at'] ?? null,
            'view_count' => 0,
            'interaction_count' => 0
        ];
        
        // Get interaction counts
        try {
            $thirty_days_ago = new MongoDB\BSON\UTCDateTime((time() - (30 * 24 * 60 * 60)) * 1000);
            
            // Count views
            $item_data['view_count'] = $db->interactions->countDocuments([
                'tenant_id' => $item['tenant_id'],
                'item_id' => $item['item_id'],
                'event_type' => 'view',
                'ts' => ['$gte' => $thirty_days_ago]
            ]);
            
            // Count all interactions
            $item_data['interaction_count'] = $db->interactions->countDocuments([
                'tenant_id' => $item['tenant_id'],
                'item_id' => $item['item_id'],
                'ts' => ['$gte' => $thirty_days_ago]
            ]);
            
        } catch (Exception $e) {
            error_log("Error getting item stats for {$item['item_id']}: " . $e->getMessage());
        }
        
        $items[] = $item_data;
    }
    
    // Get item statistics
    $item_stats = [
        'total' => $total_items,
        'with_interactions' => 0,
        'by_type' => []
    ];
    
    // Get type distribution
    try {
        $type_pipeline = [
            ['$group' => ['_id' => '$type', 'count' => ['$sum' => 1]]],
            ['$sort' => ['count' => -1]]
        ];
        $type_results = $db->items->aggregate($type_pipeline)->toArray();
        foreach ($type_results as $result) {
            $item_stats['by_type'][$result['_id']] = $result['count'];
        }
    } catch (Exception $e) {
        error_log("Error getting item type stats: " . $e->getMessage());
    }
    
    // Get recent items
    $recent_items = [];
    try {
        $recent_cursor = $db->items->find([], [
            'sort' => ['created_at' => -1],
            'limit' => 5,
            'projection' => ['item_id' => 1, 'title' => 1, 'type' => 1, 'tenant_id' => 1, 'created_at' => 1]
        ]);
        
        foreach ($recent_cursor as $item) {
            $recent_items[] = [
                'item_id' => $item['item_id'],
                'title' => $item['title'] ?? $item['name'] ?? 'Untitled',
                'type' => $item['type'] ?? 'unknown',
                'tenant_id' => $item['tenant_id'],
                'created_at' => $item['created_at']
            ];
        }
    } catch (Exception $e) {
        error_log("Error getting recent items: " . $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("Items data error: " . $e->getMessage());
    
    // Fallback data
    $items = [];
    $item_stats = ['total' => 0, 'with_interactions' => 0, 'by_type' => []];
    $recent_items = [];
    $tenants_list = [];
    $total_pages = 1;
    $error_message = "Failed to load items data: " . $e->getMessage();
}

?>
