<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class NotificationController extends Controller
{
    public function index(Request $request): View
    {
        /** @var User $user */
        $user = Auth::user();
        $notifications = $user
            ->notifications()
            ->latest()
            ->paginate(20)
            ->withQueryString();

        return view('customer.notifications.index', compact('notifications'));
    }

    public function markAsRead(string $notificationId): RedirectResponse
    {
        /** @var User $user */
        $user = Auth::user();
        $notification = $user
            ->notifications()
            ->where('id', $notificationId)
            ->firstOrFail();

        if (is_null($notification->read_at)) {
            $notification->markAsRead();
        }

        $redirectUrl = data_get($notification->data, 'url');
        if (is_string($redirectUrl) && $redirectUrl !== '') {
            return redirect($redirectUrl);
        }

        return back()->with('success', 'Notification marked as read.');
    }

    public function markAllAsRead(): RedirectResponse
    {
        /** @var User $user */
        $user = Auth::user();
        $user->unreadNotifications->markAsRead();

        return back()->with('success', 'All notifications marked as read.');
    }
}
