<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../services/notifications/NotificationService.php';

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

try {
    $userId = current_user_id();
    $service = new NotificationService(db());
    $items = $service->recent($userId, isset($_GET['limit']) ? (int)$_GET['limit'] : 10);

    echo json_encode([
        'success' => true,
        'unread_count' => $service->unreadCount($userId),
        'notifications' => array_map(function ($item) {
            return [
                'id' => (int)$item['id'],
                'event_type' => $item['event_type'],
                'title' => $item['title'],
                'body' => $item['body'],
                'url' => $item['url'],
                'priority' => $item['priority'],
                'read_at' => $item['read_at'],
                'created_at' => $item['created_at'],
            ];
        }, $items),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
