<?php

namespace AleshaCMS\Http\Middleware;

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

class InjectCmsSignature
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        if (
            $response instanceof \Illuminate\Http\Response &&
            str_contains($response->headers->get('Content-Type', ''), 'text/html')
        ) {
            $content = $response->getContent();
            if ($content && str_contains($content, '</head>')) {
                $content = preg_replace('/<meta[^>]+name=["\']generator["\'][^>]*>/i', '', $content);
                $content = str_replace(
                    '</head>',
                    "    <meta name=\"generator\" content=\"AleshaCMS\">\n</head>",
                    $content
                );
                $response->setContent($content);
            }
        }

        return $response;
    }
}
