<?php
// api/news_notifications.php

declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/news_common.php';

try {
    rvu_ensure_news_tables($pdo);
    $user = rvu_news_require_user($pdo);
    $userId = (int)$user['id'];
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
    $path = trim((string)($_SERVER['PATH_INFO'] ?? ''), '/');
    $notificationId = ctype_digit($path) ? (int)$path : null;

    if ($method === 'GET') {
        $limit = max(1, min(100, (int)($_GET['limit'] ?? 30)));
        rvu_news_json([
            'notifications' => rvu_news_fetch_notifications($pdo, $userId, $limit),
            'unread_count' => rvu_news_unread_notification_count($pdo, $userId),
        ]);
    }

    if ($method === 'POST') {
        $input = rvu_news_input();
        if (($input['action'] ?? '') !== 'mark_all_read') {
            rvu_news_json(['detail' => 'Unsupported action.'], 422);
        }
        $stmt = $pdo->prepare('UPDATE campus_news_notifications SET is_read = TRUE WHERE recipient_user_id = ?');
        $stmt->execute([$userId]);
        rvu_news_json(['success' => true]);
    }

    if ($method === 'PUT' && $notificationId !== null) {
        $input = rvu_news_input();
        $isRead = rvu_news_bool($input['is_read'] ?? true);
        $stmt = $pdo->prepare('UPDATE campus_news_notifications SET is_read = ? WHERE id = ? AND recipient_user_id = ?');
        $stmt->execute([$isRead, $notificationId, $userId]);
        rvu_news_json(['success' => true]);
    }

    rvu_news_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_news_json(['detail' => 'News notification server error: ' . $e->getMessage()], 500);
}
