<?php
/**
 * KSO Chandigarh Admin Panel
 * Assignment Stream API Endpoint
 * 
 * This endpoint uses Server-Sent Events (SSE) to provide real-time updates 
 * about assignment changes to the client.
 */

// Include authentication and database
require_once '../../config/auth_enhanced.php';
require_once '../../config/database.php';

// Check authentication
checkAuthentication();

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

// Disable output buffering
if (ob_get_level()) {
    ob_end_clean();
}

// Function to send SSE event
function sendEvent($eventName, $data) {
    echo "event: {$eventName}\n";
    echo "data: " . json_encode($data) . "\n\n";
    flush();
}

// Send initial connection established event
sendEvent('connection_established', [
    'message' => 'Connection established',
    'timestamp' => date('Y-m-d H:i:s')
]);

// Get database connection
$database = new Database();
$conn = $database->getConnection();

// Track last seen assignment event
$lastEventId = isset($_SERVER['HTTP_LAST_EVENT_ID']) ? $_SERVER['HTTP_LAST_EVENT_ID'] : 0;
$lastEventTimestamp = time();

// Keep connection open indefinitely
set_time_limit(0);
ignore_user_abort(true);

// Main SSE loop
while (true) {
    // Check for new assignment events
    try {
        // Query for new events since last check
        $stmt = $conn->prepare("
            SELECT 
                ae.id, 
                ae.assignment_id, 
                ae.action, 
                ae.admin_id,
                ae.timestamp,
                a.title,
                a.member_id,
                CONCAT(m.first_name, ' ', m.last_name) as member_name,
                CONCAT(adm.first_name, ' ', adm.last_name) as admin_name
            FROM 
                assignment_events ae
            JOIN 
                admin_assignments a ON ae.assignment_id = a.id
            JOIN 
                members m ON a.member_id = m.id
            JOIN 
                admins adm ON ae.admin_id = adm.id
            WHERE 
                ae.id > :lastEventId
            ORDER BY 
                ae.id ASC
        ");
        
        $stmt->bindParam(':lastEventId', $lastEventId);
        $stmt->execute();
        
        $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Process and send any new events
        foreach ($events as $event) {
            // Update last event id
            $lastEventId = $event['id'];
            
            // Send the event to the client
            sendEvent('assignment_update', [
                'id' => $event['assignment_id'],
                'title' => $event['title'],
                'member_id' => $event['member_id'],
                'member_name' => $event['member_name'],
                'admin_name' => $event['admin_name'],
                'action' => $event['action'],
                'timestamp' => $event['timestamp']
            ]);
        }
        
        // Send a heartbeat every 30 seconds to keep connection alive
        if (time() - $lastEventTimestamp >= 30) {
            sendEvent('heartbeat', [
                'timestamp' => date('Y-m-d H:i:s')
            ]);
            $lastEventTimestamp = time();
        }
        
        // Clear db connection to prevent timeouts
        $conn = null;
        $conn = $database->getConnection();
        
    } catch (Exception $e) {
        // Log error and continue
        error_log('SSE Error: ' . $e->getMessage());
        
        // Send error event
        sendEvent('error', [
            'message' => 'An error occurred, reconnecting...',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
        
        // Reset database connection
        $conn = null;
        $conn = $database->getConnection();
    }
    
    // Sleep to reduce server load (2 seconds)
    sleep(2);
    
    // Check if client is still connected
    if (connection_aborted()) {
        break;
    }
}

// Close the database connection
$conn = null;
