<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Admin\PageController;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class NotificationController extends PageController
{
    public function index(Request $request): View
    {
        $notifications = $request->user()
            ->notifications()
            ->paginate(20);

        $prefix = $this->routePrefix();

        return $this->page($this->view('index'), [
            'crumbTitle' => 'Notifications',
            'crumbSub' => 'Alerts & reminders',
            'notifications' => $notifications,
            'layout' => $this->layout(),
            'readRoute' => "{$prefix}.notifications.read",
            'readAllRoute' => "{$prefix}.notifications.read-all",
        ]);
    }

    public function markRead(Request $request, string $id): RedirectResponse
    {
        $notification = $request->user()->notifications()->where('id', $id)->firstOrFail();
        $notification->markAsRead();

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

    public function markAllRead(Request $request): RedirectResponse
    {
        $request->user()->unreadNotifications->markAsRead();

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

    private function layout(): string
    {
        return match (true) {
            request()->routeIs('parent.*') => 'layouts.parent',
            request()->routeIs('student.*') => 'layouts.student',
            request()->routeIs('teacher.*') => 'layouts.teacher',
            request()->routeIs('staff.*') => 'layouts.staff',
            default => 'layouts.app',
        };
    }

    private function view(string $name): string
    {
        return "{$this->routePrefix()}.notifications.{$name}";
    }

    private function routePrefix(): string
    {
        return match (true) {
            request()->routeIs('parent.*') => 'parent',
            request()->routeIs('student.*') => 'student',
            request()->routeIs('teacher.*') => 'teacher',
            request()->routeIs('staff.*') => 'staff',
            default => 'admin',
        };
    }
}
