<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\AppNotification;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class NotificationController extends Controller
{
    public function index(): View
    {
        $tenantAlertQuery = AppNotification::whereNull('user_id');
        $memberAlertQuery = AppNotification::with('user')->whereNotNull('user_id');

        return view('tenant.notifications.index', [
            'tenantNotifications' => (clone $tenantAlertQuery)->latest()->paginate(15, ['*'], 'tenant_alerts_page'),
            'memberNotifications' => (clone $memberAlertQuery)->latest()->paginate(15, ['*'], 'member_alerts_page'),
            'tenantUnreadCount' => (clone $tenantAlertQuery)->whereNull('read_at')->count(),
            'tenantReadCount' => (clone $tenantAlertQuery)->whereNotNull('read_at')->count(),
            'memberUnreadCount' => (clone $memberAlertQuery)->whereNull('read_at')->count(),
            'memberReadCount' => (clone $memberAlertQuery)->whereNotNull('read_at')->count(),
        ]);
    }

    public function markRead(AppNotification $notification): RedirectResponse
    {
        if ($notification->user_id) {
            return back()->with('warning', 'Member alerts are shown as delivery history. They are marked read from the member portal.');
        }

        $notification->update(['read_at' => now()]);

        return back()->with('status', 'Notification marked as read.');
    }
}
