<?php
declare(strict_types=1);
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/events_common.php';

try {
    rvu_ensure_event_social_tables($pdo);
    $user = rvu_event_require_user($pdo);
    $userId = (int)$user['id'];
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'GET') {
        $limit = max(1, min(50, (int)($_GET['limit'] ?? 30)));
        $sql = "SELECT
            n.id, n.event_id, n.comment_id, n.type, n.title, n.message, n.is_read, n.created_at,
            COALESCE(u.full_name, '') AS actor_name,
            COALESCE(u.profile_picture, '') AS actor_profile_picture
          FROM campus_event_notifications n
          LEFT JOIN users u ON u.id = n.actor_user_id
          WHERE n.recipient_user_id = ?
          ORDER BY n.created_at DESC, n.id DESC
          LIMIT {$limit}";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$userId]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        foreach ($rows as &$row) {
            $row['id'] = (int)$row['id'];
            $row['event_id'] = $row['event_id'] !== null ? (int)$row['event_id'] : null;
            $row['comment_id'] = $row['comment_id'] !== null ? (int)$row['comment_id'] : null;
            $row['is_read'] = rvu_event_bool($row['is_read']);
        }
        unset($row);
        $countStmt = $pdo->prepare('SELECT COUNT(*) FROM campus_event_notifications WHERE recipient_user_id = ? AND is_read = FALSE');
        $countStmt->execute([$userId]);
        rvu_event_json(['data' => $rows, 'unread_count' => (int)$countStmt->fetchColumn()]);
    }

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

    if ($method === 'PUT') {
        $id = (int)($_GET['id'] ?? 0);
        if ($id <= 0) rvu_event_json(['detail' => 'Notification id is required.'], 422);
        $input = rvu_event_input();
        $isRead = rvu_event_bool($input['is_read'] ?? true);
        $pdo->prepare('UPDATE campus_event_notifications SET is_read = ? WHERE id = ? AND recipient_user_id = ?')->execute([$isRead, $id, $userId]);
        rvu_event_json(['success' => true]);
    }

    rvu_event_json(['detail' => 'Method not allowed.'], 405);
} catch (Throwable $e) {
    rvu_event_json(['detail' => 'Event notifications server error: ' . $e->getMessage()], 500);
}
