<?php
/**
 * API endpoint لجلب التنبيهات
 */
session_start();
require 'config.php';

// ✅ دالة shutdown لمعالجة الأخطاء القاتلة (Fatal Errors)
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && ($error['type'] === E_ERROR || $error['type'] === E_PARSE || $error['type'] === E_CORE_ERROR || $error['type'] === E_COMPILE_ERROR)) {
        if (ob_get_length()) ob_clean();
        http_response_code(500);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['status' => 'error', 'message' => 'حدث خطأ قاتل: ' . $error['message']], JSON_UNESCAPED_UNICODE);
        exit;
    }
});
require 'alerts_service.php';

header('Content-Type: application/json; charset=UTF-8');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'غير مسموح']);
    exit;
}

$alertService = new AlertService($conn, $_SESSION['user_id']);
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;

$alerts = $alertService->getUnreadAlerts($limit);

echo json_encode([
    'status' => 'success',
    'alerts' => $alerts,
    'count' => count($alerts)
], JSON_UNESCAPED_UNICODE);

