<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        $notifications = $user
            ->notifications()
            ->latest()
            ->paginate(20);

        $unreadCount = $user
            ->unreadNotifications()
            ->count();

        // Admin keeps the existing admin notification page.
        // Clients get the mobile-first notification page.
        $view = $user->role === 'admin'
            ? 'notifications.index'
            : 'notifications.client';

        return view($view, compact(
            'notifications',
            'unreadCount'
        ));
    }

    public function read(string $id)
    {
        $notification = Auth::user()
            ->notifications()
            ->where('id', $id)
            ->firstOrFail();

        $notification->markAsRead();

        $loanId = data_get($notification->data, 'loan_id');

        if ($loanId) {
            if (Auth::user()->role === 'admin') {
                return redirect()->route(
                    'admin.loans.show',
                    $loanId
                );
            }

            return redirect()->route(
                'client.loans.show',
                $loanId
            );
        }

        return redirect()->route('notifications.index');
    }

    public function readAll()
    {
        Auth::user()
            ->unreadNotifications
            ->markAsRead();

        return back()->with(
            'success',
            'All notifications marked as read.'
        );
    }
}
