<?php
require_once __DIR__ . '/connect_common.php';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') connect_json(204);
$user = connect_user($pdo);
$userId = (int)($user['id'] ?? 0);
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

try {
    if ($method === 'GET') {
        $mode = strtolower(connect_text($_GET['mode'] ?? 'list', 30));
        if ($mode === 'count') {
            $stmt = $pdo->prepare('SELECT COUNT(*) FROM connect_notifications WHERE recipient_id = ? AND is_read = FALSE');
            $stmt->execute([$userId]);
            connect_json(200, ['unread_count' => (int)$stmt->fetchColumn()]);
        }

        $limit = max(1, min(100, (int)($_GET['limit'] ?? 50)));
        $stmt = $pdo->prepare("SELECT id, actor_name, actor_email, type, title, body, post_id, comment_id, community_id, is_read, created_at
                              FROM connect_notifications
                              WHERE recipient_id = ?
                              ORDER BY created_at DESC, id DESC
                              LIMIT ?");
        $stmt->bindValue(1, $userId, PDO::PARAM_INT);
        $stmt->bindValue(2, $limit, PDO::PARAM_INT);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as &$row) {
            $row['is_read'] = connect_bool($row['is_read'] ?? false);
            $row['id'] = (int)$row['id'];
            $row['post_id'] = $row['post_id'] !== null ? (int)$row['post_id'] : null;
            $row['comment_id'] = $row['comment_id'] !== null ? (int)$row['comment_id'] : null;
            $row['community_id'] = $row['community_id'] !== null ? (int)$row['community_id'] : null;
        }
        unset($row);
        connect_json(200, ['data' => $rows]);
    }

    if ($method !== 'POST') connect_json(405, ['detail' => 'Only GET and POST are supported for notifications.']);
    $body = connect_body();
    $action = strtolower(connect_text($body['action'] ?? '', 40));

    if ($action === 'mark_all_read') {
        $stmt = $pdo->prepare('UPDATE connect_notifications SET is_read = TRUE WHERE recipient_id = ? AND is_read = FALSE');
        $stmt->execute([$userId]);
        connect_json(200, ['message' => 'Notifications marked as read.', 'unread_count' => 0]);
    }

    if ($action === 'mark_read') {
        $notificationId = (int)($body['notification_id'] ?? 0);
        if ($notificationId <= 0) connect_json(400, ['detail' => 'notification_id is required.']);
        $stmt = $pdo->prepare('UPDATE connect_notifications SET is_read = TRUE WHERE id = ? AND recipient_id = ?');
        $stmt->execute([$notificationId, $userId]);
        connect_json(200, ['message' => 'Notification marked as read.']);
    }

    connect_json(400, ['detail' => 'Unsupported notification action.']);
} catch (Throwable $e) {
    connect_json(500, ['detail' => 'Notification service error: ' . $e->getMessage()]);
}
