<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    // Ambil notif untuk user yang login (untuk badge & dropdown)
    public function index()
    {
        $role  = auth()->user()->role;
        $notifs = Notification::where('for_role', $role)
            ->orWhere('for_role', 'all')
            ->orderBy('created_at', 'desc')
            ->limit(15)
            ->get();

        $unread = $notifs->where('dibaca', false)->count();

        return response()->json([
            'notifs' => $notifs,
            'unread' => $unread,
        ]);
    }

    // Tandai semua sudah dibaca
    public function readAll()
    {
        $role = auth()->user()->role;
        Notification::where('for_role', $role)
            ->orWhere('for_role', 'all')
            ->where('dibaca', false)
            ->update(['dibaca' => true]);

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

    // Tandai satu notif sudah dibaca
    public function read($id)
    {
        Notification::where('id', $id)->update(['dibaca' => true]);
        return response()->json(['success' => true]);
    }
}
