<?php

namespace App\Http\Controllers;

use App\Models\UserNotification;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class NotificationController extends Controller
{
    public function index(Request $request)
    {
        $notifications = UserNotification::query()
            ->where('user_id', $request->user()->id)
            ->latest()
            ->paginate(20);

        return view('notifications.index', compact('notifications'));
    }

    public function markRead(Request $request, UserNotification $notification): RedirectResponse
    {
        abort_unless($notification->user_id === $request->user()->id, 403);

        if ($notification->read_at === null) {
            $notification->update(['read_at' => now()]);
        }

        $redirectTo = $request->input('redirect_to');
        if (is_string($redirectTo) && $redirectTo !== '' && $this->isSafeRedirectTarget($redirectTo, $request)) {
            return redirect($redirectTo);
        }

        return back();
    }

    public function markAllRead(Request $request): RedirectResponse
    {
        UserNotification::query()
            ->where('user_id', $request->user()->id)
            ->whereNull('read_at')
            ->update(['read_at' => now()]);

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

    private function isSafeRedirectTarget(string $target, Request $request): bool
    {
        if (Str::startsWith($target, '/') && ! Str::startsWith($target, '//')) {
            return true;
        }

        if (! filter_var($target, FILTER_VALIDATE_URL)) {
            return false;
        }

        $targetHost = parse_url($target, PHP_URL_HOST);
        $targetScheme = parse_url($target, PHP_URL_SCHEME);

        return $targetHost === $request->getHost()
            && in_array($targetScheme, ['http', 'https'], true);
    }
}
