<?php

/**
 * Route pour marquer toutes les notifications comme lues.
 * Parcourt tous les projets accessibles à l'utilisateur.
 */
return [
    'pattern' => '(:all)mark-all-notifications-read.json',
    'method' => 'POST',
    'action' => function () {
        try {
            $user = kirby()->user();
            if (!$user) {
                throw new Exception('User not authenticated');
            }

            $collector = kirby()->option('adrienpayet.pdc-notifications.collector');
            if (!$collector) {
                throw new Exception('NotificationCollector not initialized');
            }

            // Récupérer les projets selon le rôle
            if ($user->role()->name() === 'admin') {
                $projects = page('projects')->children()->toArray();
            } else {
                $projects = $user->projects()->toPages()->toArray();
            }

            $count = $collector->markAllAsRead($projects, $user);

            return json_encode([
                'status' => 'success',
                'message' => "$count notifications marked as read"
            ]);
        } catch (\Throwable $th) {
            return json_encode([
                'status' => 'error',
                'message' => $th->getMessage()
            ]);
        }
    }
];
