<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

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

            if ($request->filled('type')) {
                $query->where('type', $request->type);
            }

            $notifications = $query->latest()->paginate(20)->withQueryString();

            // Mark displayed notifications as read
            Notification::where('user_id', auth()->id())->unread()->update(['is_read' => true]);

            return view('notifications.index', [
                'notifications' => $notifications,
                'activePage' => 'notifications',
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }

    public function markAllRead()
    {
        try {
            Notification::where('user_id', auth()->id())->unread()->update(['is_read' => true]);
            return back()->with('success', 'All notifications marked as read.');
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return back()->with('alert', 'An error occurred.');
        }
    }
}
