<?php
session_start();
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/config.php';

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

$auth = new Auth();
if (!$auth->check() || !$auth->isSuperAdmin()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

$userId = $_SESSION['user_id'];
$notification = new Notification();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf = new CSRF();
    $token = $_POST['csrf_token'] ?? '';
    if (!$csrf->verify($token)) {
        jsonResponse(false, 'Invalid CSRF token.');
    }

    $action = $_POST['action'] ?? '';
    if ($action === 'mark_all_read') {
        $notification->markAllAsRead($userId);
        jsonResponse(true, 'All notifications marked as read.');
    }
}

$notifications = $notification->getUnread($userId, 10);
$count = $notification->getUnreadCount($userId);

jsonResponse(true, 'Notifications loaded', [
    'notifications' => $notifications,
    'unread_count' => $count,
]);
