<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class RedirectMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        try {
            $path = $request->path();

            $redirect = DB::table('redirects')
                ->where('old_url', $path)
                ->orWhere('old_url', '/' . $path)
                ->first();

            if ($redirect) {
                return redirect($redirect->new_url, $redirect->type);
            }

        } catch (\Exception $e) {
            // prevent crash
            return $next($request);
        }

        return $next($request);
    }
}