<?php

namespace App\Http\Middleware;

use Closure;

class SetUtf8Encoding
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Set UTF-8 encoding for database connection
        \Illuminate\Support\Facades\DB::statement("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'");
        \Illuminate\Support\Facades\DB::statement("SET CHARACTER SET utf8mb4");
        \Illuminate\Support\Facades\DB::statement("SET character_set_client=utf8mb4");
        \Illuminate\Support\Facades\DB::statement("SET character_set_connection=utf8mb4");
        \Illuminate\Support\Facades\DB::statement("SET character_set_results=utf8mb4");
        
        $response = $next($request);
        
        // Ensure response has UTF-8 charset header
        if (method_exists($response, 'header')) {
            $contentType = $response->headers->get('Content-Type');
            if ($contentType && stripos($contentType, 'charset') === false) {
                $response->header('Content-Type', $contentType . '; charset=utf-8');
            } elseif (!$contentType) {
                $response->header('Content-Type', 'text/html; charset=utf-8');
            }
        }
        
        return $response;
    }
}

