<?php
/**
 * Common Functions for Recora Admin Panel
 */

/**
 * Safely get value from array with default
 */
function safe_get($array, $key, $default = '') {
    return isset($array[$key]) ? $array[$key] : $default;
}

/**
 * Format number with appropriate suffix (K, M, B)
 */
function format_number($number) {
    if ($number >= 1000000000) {
        return round($number / 1000000000, 1) . 'B';
    } elseif ($number >= 1000000) {
        return round($number / 1000000, 1) . 'M';
    } elseif ($number >= 1000) {
        return round($number / 1000, 1) . 'K';
    }
    return number_format($number);
}

/**
 * Format bytes to human readable
 */
function format_bytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    
    for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
        $bytes /= 1024;
    }
    
    return round($bytes, $precision) . ' ' . $units[$i];
}

/**
 * Format MongoDB date for display
 */
function format_mongo_date($date) {
    try {
        if ($date instanceof MongoDB\BSON\UTCDateTime) {
            return $date->toDateTime()->format('Y-m-d H:i:s');
        } elseif (is_string($date)) {
            return date('Y-m-d H:i:s', strtotime($date));
        }
        return 'Unknown';
    } catch (Exception $e) {
        return 'Invalid Date';
    }
}

/**
 * Format time ago
 */
function time_ago($date) {
    try {
        if ($date instanceof MongoDB\BSON\UTCDateTime) {
            $timestamp = $date->toDateTime()->getTimestamp();
        } elseif (is_string($date)) {
            $timestamp = strtotime($date);
        } else {
            return 'Unknown';
        }
        
        $diff = time() - $timestamp;
        
        if ($diff < 60) {
            return 'just now';
        } elseif ($diff < 3600) {
            return floor($diff / 60) . ' minutes ago';
        } elseif ($diff < 86400) {
            return floor($diff / 3600) . ' hours ago';
        } elseif ($diff < 2592000) {
            return floor($diff / 86400) . ' days ago';
        } else {
            return date('M j, Y', $timestamp);
        }
    } catch (Exception $e) {
        return 'Unknown';
    }
}

/**
 * Get adapter badge HTML
 */
function get_adapter_badge($adapter) {
    $badges = [
        'ott' => '<span class="adapter-badge ott">OTT</span>',
        'retail' => '<span class="adapter-badge retail">Retail</span>',
        'pharma' => '<span class="adapter-badge pharma">Pharma</span>',
        'consulting' => '<span class="adapter-badge consulting">Consulting</span>'
    ];
    
    return $badges[$adapter] ?? '<span class="adapter-badge unknown">Unknown</span>';
}

/**
 * Get status badge HTML
 */
function get_status_badge($status) {
    $badges = [
        'active' => '<span class="status-badge active">Active</span>',
        'inactive' => '<span class="status-badge inactive">Inactive</span>',
        'suspended' => '<span class="status-badge suspended">Suspended</span>',
        'maintenance' => '<span class="status-badge maintenance">Maintenance</span>'
    ];
    
    return $badges[$status] ?? '<span class="status-badge unknown">Unknown</span>';
}

/**
 * Sanitize output for HTML
 */
function h($string) {
    return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}

/**
 * Generate pagination HTML
 */
function generate_pagination($current_page, $total_pages, $base_url) {
    if ($total_pages <= 1) return '';
    
    $html = '<div class="pagination">';
    
    // Previous button
    if ($current_page > 1) {
        $html .= '<a href="' . $base_url . '&page_num=' . ($current_page - 1) . '" class="pagination-btn">
                    <i class="fas fa-chevron-left"></i> Previous
                  </a>';
    }
    
    // Page numbers
    $start = max(1, $current_page - 2);
    $end = min($total_pages, $current_page + 2);
    
    if ($start > 1) {
        $html .= '<a href="' . $base_url . '&page_num=1" class="pagination-num">1</a>';
        if ($start > 2) {
            $html .= '<span class="pagination-dots">...</span>';
        }
    }
    
    for ($i = $start; $i <= $end; $i++) {
        $active = $i == $current_page ? 'active' : '';
        $html .= '<a href="' . $base_url . '&page_num=' . $i . '" class="pagination-num ' . $active . '">' . $i . '</a>';
    }
    
    if ($end < $total_pages) {
        if ($end < $total_pages - 1) {
            $html .= '<span class="pagination-dots">...</span>';
        }
        $html .= '<a href="' . $base_url . '&page_num=' . $total_pages . '" class="pagination-num">' . $total_pages . '</a>';
    }
    
    // Next button
    if ($current_page < $total_pages) {
        $html .= '<a href="' . $base_url . '&page_num=' . ($current_page + 1) . '" class="pagination-btn">
                    Next <i class="fas fa-chevron-right"></i>
                  </a>';
    }
    
    $html .= '</div>';
    return $html;
}

/**
 * Get collection count with caching
 */
function get_collection_count($collection_name, $filter = []) {
    static $cache = [];
    $cache_key = $collection_name . '_' . md5(json_encode($filter));
    
    if (!isset($cache[$cache_key])) {
        try {
            $collection = MongoDBConnection::getInstance()->getCollection($collection_name);
            $cache[$cache_key] = $collection->countDocuments($filter);
        } catch (Exception $e) {
            error_log("Error counting $collection_name: " . $e->getMessage());
            $cache[$cache_key] = 0;
        }
    }
    
    return $cache[$cache_key];
}

/**
 * Get recent activity from multiple collections
 */
function get_recent_activity($limit = 10) {
    $activities = [];
    
    try {
        $db = MongoDBConnection::getInstance()->getDatabase();
        
        // Get recent tenant additions
        $tenants = $db->tenants->find([], [
            'sort' => ['created_at' => -1],
            'limit' => 5,
            'projection' => ['name' => 1, 'created_at' => 1]
        ]);
        
        foreach ($tenants as $tenant) {
            $activities[] = [
                'type' => 'tenant_created',
                'message' => 'New tenant "' . $tenant['name'] . '" created',
                'timestamp' => $tenant['created_at'],
                'icon' => 'fas fa-building'
            ];
        }
        
        // Get recent app additions
        $apps = $db->apps->find([], [
            'sort' => ['created_at' => -1],
            'limit' => 5,
            'projection' => ['name' => 1, 'adapter' => 1, 'created_at' => 1]
        ]);
        
        foreach ($apps as $app) {
            $activities[] = [
                'type' => 'app_created',
                'message' => 'New ' . strtoupper($app['adapter']) . ' app "' . $app['name'] . '" created',
                'timestamp' => $app['created_at'],
                'icon' => 'fas fa-mobile-alt'
            ];
        }
        
        // Sort by timestamp and limit
        usort($activities, function($a, $b) {
            return $b['timestamp'] <=> $a['timestamp'];
        });
        
        return array_slice($activities, 0, $limit);
        
    } catch (Exception $e) {
        error_log("Error getting recent activity: " . $e->getMessage());
        return [];
    }
}

/**
 * Get adapter statistics
 */
function get_adapter_stats() {
    try {
        $collection = MongoDBConnection::getInstance()->getCollection('apps');
        
        $pipeline = [
            [
                '$group' => [
                    '_id' => '$adapter',
                    'count' => ['$sum' => 1]
                ]
            ],
            [
                '$sort' => ['count' => -1]
            ]
        ];
        
        $results = $collection->aggregate($pipeline)->toArray();
        
        $stats = [];
        foreach ($results as $result) {
            $stats[$result['_id']] = $result['count'];
        }
        
        return $stats;
        
    } catch (Exception $e) {
        error_log("Error getting adapter stats: " . $e->getMessage());
        return [];
    }
}

/**
 * Format JSON for display
 */
function format_json($json, $pretty = true) {
    if (is_array($json) || is_object($json)) {
        $json = json_encode($json, $pretty ? JSON_PRETTY_PRINT : 0);
    }
    
    if ($pretty) {
        return '<pre class="json-display">' . h($json) . '</pre>';
    }
    
    return h($json);
}

/**
 * Get performance metrics
 */
function get_performance_metrics($days = 7) {
    try {
        $collection = MongoDBConnection::getInstance()->getCollection('interactions');
        
        $start_date = new MongoDB\BSON\UTCDateTime((time() - ($days * 24 * 60 * 60)) * 1000);
        
        $pipeline = [
            [
                '$match' => [
                    'ts' => ['$gte' => $start_date]
                ]
            ],
            [
                '$group' => [
                    '_id' => [
                        'date' => [
                            '$dateToString' => [
                                'format' => '%Y-%m-%d',
                                'date' => '$ts'
                            ]
                        ],
                        'event_type' => '$event_type'
                    ],
                    'count' => ['$sum' => 1]
                ]
            ],
            [
                '$sort' => ['_id.date' => 1]
            ]
        ];
        
        $results = $collection->aggregate($pipeline)->toArray();
        
        $metrics = [];
        foreach ($results as $result) {
            $date = $result['_id']['date'];
            $event_type = $result['_id']['event_type'];
            $count = $result['count'];
            
            if (!isset($metrics[$date])) {
                $metrics[$date] = [];
            }
            $metrics[$date][$event_type] = $count;
        }
        
        return $metrics;
        
    } catch (Exception $e) {
        error_log("Error getting performance metrics: " . $e->getMessage());
        return [];
    }
}

/**
 * Escape MongoDB regex
 */
function escape_mongo_regex($string) {
    return preg_quote($string, '/');
}

/**
 * Build MongoDB filter from search parameters
 */
function build_search_filter($search_params) {
    $filter = [];
    
    if (!empty($search_params['search'])) {
        $search = escape_mongo_regex($search_params['search']);
        $filter['$or'] = [
            ['name' => new MongoDB\BSON\Regex($search, 'i')],
            ['title' => new MongoDB\BSON\Regex($search, 'i')],
            ['description' => new MongoDB\BSON\Regex($search, 'i')]
        ];
    }
    
    if (!empty($search_params['status'])) {
        $filter['status'] = $search_params['status'];
    }
    
    if (!empty($search_params['adapter'])) {
        $filter['adapter'] = $search_params['adapter'];
    }
    
    if (!empty($search_params['tenant_id'])) {
        $filter['tenant_id'] = $search_params['tenant_id'];
    }
    
    return $filter;
}

?>
