<?php
require_once 'includes/init.php';

if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

$userId = $_SESSION['user_id'];
$db = getDB();

// Track last activity
$stmt = $db->prepare("UPDATE users SET last_activity = NOW() WHERE id = ?");
$stmt->execute([$userId]);

// Check for new messages
$stmt = $db->prepare("
    SELECT COUNT(*) as count 
    FROM messages m
    WHERE m.receiver_id = ? 
    AND m.id NOT IN (
        SELECT ms.message_id 
        FROM message_status ms 
        WHERE ms.user_id = ? AND ms.status = 'read'
    )
    AND m.deleted_by_receiver = 0 
    AND m.is_deleted_for_all = 0
    AND m.created_at > DATE_SUB(NOW(), INTERVAL 1 SECOND)
");
$stmt->execute([$userId, $userId]);
$newMessages = $stmt->fetch();

// Check for new announcements
$stmt = $db->prepare("
    SELECT COUNT(*) as count
    FROM announcements a
    WHERE a.is_active = 1
    AND a.id NOT IN (
        SELECT ar.announcement_id 
        FROM announcement_reads ar 
        WHERE ar.user_id = ? AND ar.is_read = 1
    )
    AND a.created_at > DATE_SUB(NOW(), INTERVAL 1 SECOND)
");
$stmt->execute([$userId]);
$newAnnouncements = $stmt->fetch();

// Send notification if there are new messages or announcements
if ($newMessages['count'] > 0 || $newAnnouncements['count'] > 0) {
    $data = [
        'type' => 'notification',
        'new_messages' => (int)$newMessages['count'],
        'new_announcements' => (int)$newAnnouncements['count'],
        'timestamp' => time()
    ];
    echo "data: " . json_encode($data) . "\n\n";
    flush();
}

// Check for typing indicators
$stmt = $db->prepare("
    SELECT DISTINCT 
        u.name,
        u.unique_id,
        t.is_typing
    FROM typing_indicators t
    JOIN users u ON u.id = t.user_id
    WHERE t.receiver_id = ? 
    AND t.is_typing = 1
    AND t.created_at > DATE_SUB(NOW(), INTERVAL 3 SECOND)
");
$stmt->execute([$userId]);
$typingUsers = $stmt->fetchAll();

if (!empty($typingUsers)) {
    foreach ($typingUsers as $user) {
        $data = [
            'type' => 'typing',
            'user' => [
                'name' => $user['name'],
                'unique_id' => $user['unique_id']
            ],
            'timestamp' => time()
        ];
        echo "data: " . json_encode($data) . "\n\n";
        flush();
    }
}

// Send periodic keep-alive
echo "data: {\"type\": \"keepalive\", \"timestamp\": " . time() . "}\n\n";
flush();
?>
