<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class NoIndexAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        // Only apply to /admin routes
        if ($request->is('admin*')) {
            // For HTML responses, inject meta tag
            if (
                $response->headers->get('Content-Type') &&
                str_contains($response->headers->get('Content-Type'), 'text/html')
            ) {

                $content = $response->getContent();

                // Inject <meta name="robots" content="noindex, nofollow"> inside <head>
                $content = preg_replace(
                    '/<head(.*?)>/i',
                    '<head$1><meta name="robots" content="noindex, nofollow">',
                    $content,
                    1
                );

                $response->setContent($content);
            }

            // Also set HTTP header for crawlers (works for non-HTML requests too)
            $response->headers->set('X-Robots-Tag', 'noindex, nofollow');
        }

        return $response;
    }
}
