<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AdminNotificationController extends Controller
{
   public function index(Request $request)
{
    $user = $request->user();

    return response()->json([
        'unread_count' => $user->unreadNotifications()->count(),
        'items' => $user->notifications()
            ->latest()
            ->limit(30)
            ->get()
            ->map(fn($n) => [
                'id'      => $n->id,
                'read'    => $n->read_at !== null,
                'title'   => data_get($n->data, 'title'),
                'message' => data_get($n->data, 'message'),
                'meta'    => data_get($n->data, 'meta', []),
                'time'    => $n->created_at->diffForHumans(),
                'created_at_iso' => $n->created_at->toIso8601String(),
            ]),
    ]);
}


    public function markRead(Request $request, string $id)
    {
        $n = $request->user()->notifications()->whereKey($id)->firstOrFail();
        $n->markAsRead();

        return response()->json(['ok' => true]);
    }

    public function markAllRead(Request $request)
    {
        $request->user()->unreadNotifications->markAsRead();

        return response()->json(['ok' => true]);
    }
}
