<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class JavascriptInjector implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // 실행 전 로직 불필요
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // HTML 응답일 때만 실행
        if (strpos($response->getHeaderLine('Content-Type'), 'text/html') === false) return;

        // .env에서 서버 이름 가져오기 (없으면 'Unknown' 또는 컨테이너ID)
        $serverAlias = env('APP_SERVER_NAME') ?? gethostname();
        $envMode = ENVIRONMENT; 

        $scriptTag = "
        <script>
            var SERVER_INFO = {
                alias: '{$serverAlias}',
                env: '{$envMode}'
            };
        </script>
        <script src='/common/js/de.js'></script>";

        $body = $response->getBody();
        if (strpos($body, '</body>') !== false) {
            $response->setBody(str_replace('</body>', $scriptTag . '</body>', $body));
        }
    }
}