<?php
/**
 * Real-time Notifications via Server-Sent Events
 */

$config = require __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../src/Core/Database.php';
require_once __DIR__ . '/../../src/Core/Auth.php';
require_once __DIR__ . '/../../src/Core/RealTime/ServerSentEvents.php';

// التحقق من المصادقة
$db = \App\Core\Database::getInstance($config['db'])->connection();
$auth = new \App\Core\Auth($db);

if (!$auth->check()) {
    http_response_code(401);
    exit;
}

$userId = $_SESSION['user_id'] ?? 0;
$sse = new \App\Core\RealTime\ServerSentEvents();

// إرسال ping كل 30 ثانية
$lastPing = time();
$pingInterval = 30;

// إرسال notifications جديدة
$lastNotificationId = (int)($_GET['last_id'] ?? 0);

while (true) {
    // التحقق من connection
    if (connection_aborted()) {
        break;
    }

    // جلب notifications جديدة
    try {
        $stmt = $db->prepare("
            SELECT id, type, message, created_at
            FROM notifications
            WHERE user_id = ? AND id > ?
            ORDER BY id ASC
            LIMIT 10
        ");
        $stmt->execute([$userId, $lastNotificationId]);
        $notifications = $stmt->fetchAll();

        foreach ($notifications as $notification) {
            $sse->send('notification', [
                'id' => $notification['id'],
                'type' => $notification['type'],
                'message' => $notification['message'],
                'created_at' => $notification['created_at']
            ], (string)$notification['id']);
            
            $lastNotificationId = $notification['id'];
        }
    } catch (\Throwable $e) {
        error_log("SSE error: " . $e->getMessage());
    }

    // إرسال ping
    if (time() - $lastPing >= $pingInterval) {
        $sse->ping();
        $lastPing = time();
    }

    sleep(2); // Check every 2 seconds
}

$sse->close();
