<?php
// api/request_notifications.php
// Authenticated notifications for the official request-routing workflow.

require_once __DIR__ . '/request_workflow_common.php';

try {
    rvu_req_ensure_tables($pdo);
    $user = rvu_req_user($pdo);
    $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

    if ($method === 'GET') {
        $action = strtolower(trim((string)($_GET['action'] ?? '')));
        if ($action === 'count') {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM workflow_request_notifications WHERE recipient_user_id = ? AND is_read = FALSE");
            $stmt->execute([(int)$user['id']]);
            rvu_req_json(['unread_count' => (int)$stmt->fetchColumn()]);
        }

        $unreadOnly = ((string)($_GET['unread_only'] ?? '0')) === '1';
        $sql = "SELECT n.*, r.reference, r.status, r.target_campus, r.recipient_position
                FROM workflow_request_notifications n
                INNER JOIN workflow_requests r ON r.id = n.request_id
                WHERE n.recipient_user_id = ?";
        if ($unreadOnly) $sql .= ' AND n.is_read = FALSE';
        $sql .= ' ORDER BY n.created_at DESC, n.id DESC LIMIT 100';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([(int)$user['id']]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        foreach ($rows as &$row) {
            $row['id'] = (int)$row['id'];
            $row['request_id'] = (int)$row['request_id'];
            $row['recipient_user_id'] = (int)$row['recipient_user_id'];
            $row['is_read'] = $row['is_read'] === true || $row['is_read'] === 't' || $row['is_read'] === 1 || $row['is_read'] === '1';
        }
        unset($row);
        rvu_req_json(['data' => $rows]);
    }

    if ($method === 'PUT') {
        $input = rvu_req_input();
        $action = strtolower(rvu_req_clean($input['action'] ?? '', 40));
        if ($action === 'mark_all_read') {
            $stmt = $pdo->prepare("UPDATE workflow_request_notifications SET is_read = TRUE, read_at = COALESCE(read_at, CURRENT_TIMESTAMP) WHERE recipient_user_id = ? AND is_read = FALSE");
            $stmt->execute([(int)$user['id']]);
            rvu_req_json(['message' => 'All request notifications marked as read.']);
        }
        if ($action === 'mark_read') {
            $id = (int)($input['id'] ?? 0);
            if ($id <= 0) rvu_req_json(['detail' => 'A valid notification ID is required.'], 400);
            $stmt = $pdo->prepare("UPDATE workflow_request_notifications SET is_read = TRUE, read_at = COALESCE(read_at, CURRENT_TIMESTAMP) WHERE id = ? AND recipient_user_id = ?");
            $stmt->execute([$id, (int)$user['id']]);
            rvu_req_json(['message' => 'Notification marked as read.']);
        }
        rvu_req_json(['detail' => 'Unsupported notification action.'], 422);
    }

    rvu_req_json(['detail' => 'Method not allowed.'], 405);
} catch (Throwable $e) {
    error_log('Request notification error: ' . $e->getMessage());
    rvu_req_json(['detail' => 'The request notification service encountered an unexpected server error.'], 500);
}
