<?php

namespace App\Http\Middleware;

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

class CleanJsonResponse
{
    /**
     * Handle an incoming request and ensure clean JSON responses.
     * This prevents issues on shared hosting where extra output corrupts JSON.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Clean any existing output buffers before processing request
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        // Start fresh output buffer
        ob_start();

        $response = $next($request);

        // If response is JSON, ensure it's clean
        if ($response->headers->get('Content-Type') === 'application/json' ||
            $request->expectsJson() ||
            $request->isJson()) {

            // Get any buffered output
            $bufferedOutput = ob_get_clean();

            // Get the response content
            $content = $response->getContent();

            // If there's unwanted buffered output before JSON, remove it
            if (!empty($bufferedOutput) && $bufferedOutput !== $content) {
                // Log the issue for debugging
                \Log::warning('Unwanted output detected before JSON response', [
                    'buffered_output' => substr($bufferedOutput, 0, 200),
                    'url' => $request->fullUrl()
                ]);

                // Try to extract just the JSON part
                $jsonStart = strpos($content, '{');
                $jsonStartArray = strpos($content, '[');

                if ($jsonStart !== false || $jsonStartArray !== false) {
                    // Find the first occurrence of JSON
                    $start = min(
                        $jsonStart !== false ? $jsonStart : PHP_INT_MAX,
                        $jsonStartArray !== false ? $jsonStartArray : PHP_INT_MAX
                    );

                    if ($start !== PHP_INT_MAX && $start > 0) {
                        $cleanContent = substr($content, $start);
                        $response->setContent($cleanContent);
                    }
                }
            }
        } else {
            // For non-JSON responses, clean buffer normally
            ob_end_flush();
        }

        return $response;
    }
}
