<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AddTrailingSlash
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $path = $request->getPathInfo();

        // Skip if already has trailing slash
        if (str_ends_with($path, '/')) {
            return $next($request);
        }

        // Skip if is home page
        if ($path === '') {
            return $next($request);
        }

        // Skip Inertia.js requests to prevent redirect loops
        if ($request->header('X-Inertia')) {
            return $next($request);
        }

        // Skip XML files (sitemap)
        if (str_ends_with($path, '.xml')) {
            return $next($request);
        }

        // Skip asset files
        if (preg_match('/\.(css|js|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)$/i', $path)) {
            return $next($request);
        }

        // Skip API routes or other non-web routes
        if (str_starts_with($path, '/api/') || str_starts_with($path, '/admin/')) {
            return $next($request);
        }

        // Add trailing slash and redirect with 301
        $newUrl = $request->url() . '/';
        if ($request->getQueryString()) {
            $newUrl .= '?' . $request->getQueryString();
        }

        return redirect($newUrl, 301);
    }
}
