<?php

namespace App\Http\Middleware;

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

class SetCharsetUTF8
{
    /**
     * Force UTF-8 encoding on all responses.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Set UTF-8 charset for HTML responses
        if ($response->headers->has('Content-Type')) {
            $contentType = $response->headers->get('Content-Type');
            
            // Only modify if it's HTML and doesn't already have charset
            if (str_contains($contentType, 'text/html') && !str_contains($contentType, 'charset')) {
                $response->headers->set('Content-Type', 'text/html; charset=UTF-8');
            }
        } else {
            // Default to HTML with UTF-8
            $response->headers->set('Content-Type', 'text/html; charset=UTF-8');
        }

        return $response;
    }
}
