<?php
// online.php - Realistic US Platform Traffic Counter
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-cache, must-revalidate');

class USPlatformTrafficCounter {
    public function getTrafficData() {
        $currentTime = time();
        $hour = (int)date('H');
        $minute = (int)date('i');
        $second = (int)date('s');
        $dayOfWeek = date('w'); // 0 (Sunday) to 6 (Saturday)
        
        // Generate realistic traffic count for US platform (900 - 8,000)
        $trafficCount = $this->generateUSPlatformCount($hour, $minute, $second, $dayOfWeek);
        
        // Generate trend message
        $trendMessage = $this->getTrendMessage($trafficCount);
        
        return [
            'success' => true,
            'count' => $trafficCount,
            'display_count' => $this->formatDisplayCount($trafficCount),
            'trend_message' => $trendMessage,
            'timestamp' => $currentTime,
            'timezone' => 'EST'
        ];
    }
    
    private function generateUSPlatformCount($hour, $minute, $second, $dayOfWeek) {
        // Adjusted for US audience - lower, more realistic numbers
        // Weekday vs Weekend patterns
        $isWeekend = ($dayOfWeek == 0 || $dayOfWeek == 6);
        
        // Base patterns for different times of day (EST timezone)
        $basePatterns = [
            'late_night' => [900, 1500],      // 12am-5am
            'early_morning' => [1200, 2200],  // 5am-9am
            'morning' => [2000, 3500],        // 9am-12pm
            'lunch' => [1800, 3000],          // 12pm-2pm
            'afternoon' => [2500, 4500],      // 2pm-6pm
            'evening' => [3000, 6000],        // 6pm-10pm (peak for US)
            'late_evening' => [1500, 3000]    // 10pm-12am
        ];
        
        // Weekends are 30-50% less busy
        $weekendFactor = $isWeekend ? 0.7 : 1.0;
        
        // Determine time period (EST timezone - adjust for your location)
        if ($hour >= 0 && $hour < 5) $pattern = $basePatterns['late_night'];
        elseif ($hour >= 5 && $hour < 9) $pattern = $basePatterns['early_morning'];
        elseif ($hour >= 9 && $hour < 12) $pattern = $basePatterns['morning'];
        elseif ($hour >= 12 && $hour < 14) $pattern = $basePatterns['lunch'];
        elseif ($hour >= 14 && $hour < 18) $pattern = $basePatterns['afternoon'];
        elseif ($hour >= 18 && $hour < 22) $pattern = $basePatterns['evening'];
        else $pattern = $basePatterns['late_evening'];
        
        // Apply weekend factor
        $pattern[0] = $pattern[0] * $weekendFactor;
        $pattern[1] = $pattern[1] * $weekendFactor;
        
        // Base count
        $baseCount = rand($pattern[0], $pattern[1]);
        
        // Add minute and second based micro-fluctuations (smaller variations)
        $minuteWave = sin($minute * 0.1047) * 300;
        $secondWave = cos($second * 0.2094) * 150;
        
        $totalCount = $baseCount + $minuteWave + $secondWave;
        
        // Ensure realistic range for US platform (900 - 8,000)
        return max(900, min(8000, (int)$totalCount));
    }
    
    private function formatDisplayCount($count) {
        if ($count >= 10000) {
            return number_format($count / 1000, 1) . 'k online';
        } elseif ($count >= 1000) {
            return number_format($count / 1000, 1) . 'k online';
        }
        return number_format($count) . ' online';
    }
    
    private function getTrendMessage($count) {
        // More conservative trend messages for US audience
        if ($count < 2000) return "Steady traffic";
        if ($count < 4000) return "Active now";
        if ($count < 6000) return "Peak hours";
        return "High activity";
    }
}

// Handle request
try {
    $counter = new USPlatformTrafficCounter();
    $trafficData = $counter->getTrafficData();
    
    // Add small random delay to simulate real API (5-50ms)
    usleep(rand(5000, 50000));
    
    echo json_encode($trafficData);
    
} catch (Exception $e) {
    // Conservative fallback for US platform
    $hour = (int)date('H');
    $isWeekend = (date('w') == 0 || date('w') == 6);
    
    // Lower fallback numbers
    if ($isWeekend) {
        $fallbackCount = rand(1200, 2800);
    } else {
        $fallbackCount = $hour >= 9 && $hour < 18 ? rand(2500, 4500) : rand(1500, 3000);
    }
    
    echo json_encode([
        'success' => true,
        'count' => $fallbackCount,
        'display_count' => number_format($fallbackCount) . ' online',
        'trend_message' => 'Active now',
        'timestamp' => time(),
        'timezone' => 'EST'
    ]);
}
?>