<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Redirect;

class RedirectMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $path = '/' . ltrim($request->path(), '/');

        $redirect = Redirect::where('old_url', $path)
            ->where('status', 1)
            ->first();

        if ($redirect) {

            if ($redirect->type == '404') {
                abort(404);
            }

            $url = $redirect->new_url;

            // ✅ Auto-fix external URLs
            if (!preg_match('~^https?://~i', $url) && !str_starts_with($url, '/')) {
                $url = 'https://' . ltrim($url, '/');
            }

            return redirect($url, (int)$redirect->type);
        }

        return $next($request);
    }
}
