<?php

namespace App\Http\Controllers\Api\RT;

use App\Http\Controllers\Controller;
use App\Models\Notifikasi;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NotifikasiController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Notifikasi::where('user_id', auth()->id());

        if ($request->has('is_read')) {
            $query->where('is_read', $request->boolean('is_read'));
        }

        $notifikasi = $query->orderBy('created_at', 'desc')->paginate(20);

        return response()->json($notifikasi);
    }

    public function markAsRead(Notifikasi $notifikasi): JsonResponse
    {
        if ($notifikasi->user_id !== auth()->id()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $notifikasi->update([
            'is_read' => true,
            'read_at' => now()
        ]);

        return response()->json([
            'message' => 'Notifikasi ditandai sudah dibaca',
            'data' => $notifikasi
        ]);
    }

    public function markAllAsRead(): JsonResponse
    {
        Notifikasi::where('user_id', auth()->id())
                  ->where('is_read', false)
                  ->update([
                      'is_read' => true,
                      'read_at' => now()
                  ]);

        return response()->json([
            'message' => 'Semua notifikasi ditandai sudah dibaca'
        ]);
    }

    public function unreadCount(): JsonResponse
    {
        $count = Notifikasi::where('user_id', auth()->id())
                          ->where('is_read', false)
                          ->count();

        return response()->json([
            'unread_count' => $count
        ]);
    }
}
