<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class InjectThemeVariables
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        
        // Only process HTML responses
        if ($response instanceof Response && strpos($response->headers->get('Content-Type'), 'text/html') !== false) {
            $content = $response->getContent();
            
            // Inject themeStyles and themeJson into head
            $headPos = strpos($content, '<head>');
            if ($headPos !== false) {
                $settingsService = app(\App\Services\SettingsService::class);
                
                $themeStyles = '<style>' . $settingsService->getThemeStyles() . '</style>';
                $themeJson = '<script>window.themeSettings = ' . json_encode([
                    'variables' => $settingsService->getThemeCssVariables(),
                    'mode' => $settingsService->getThemeMode(),
                    'hotelName' => $settingsService->getHotelName()
                ]) . ';</script>';
                
                $inject = "\n    " . $themeStyles . "\n    " . $themeJson . "\n    ";
                $content = substr_replace($content, $inject, $headPos + 6, 0);
            }
            
            // Inject theme-applier.js before closing body
            $bodyPos = strrpos($content, '</body>');
            if ($bodyPos !== false) {
                $inject = "\n    <script src=\"" . asset('js/theme-applier.js') . "\"></script>\n";
                $content = substr_replace($content, $inject, $bodyPos, 0);
            }
            
            $response->setContent($content);
        }
        
        return $response;
    }
}