<?php

namespace App\Support;

use Illuminate\Http\Response;
use RuntimeException;

final class LegacyPhp
{
    public static function render(string $file, array $serverOverrides = []): Response
    {
        $absolute = base_path($file);

        if (!is_file($absolute)) {
            abort(404);
        }

        $previousDirectory = getcwd();
        $directory = dirname($absolute);
        $previousServer = $_SERVER;
        $previousErrorReporting = error_reporting();

        $_SERVER = array_replace($_SERVER, $serverOverrides);

        ob_start();

        try {
            chdir($directory);
            error_reporting($previousErrorReporting & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED & ~E_USER_DEPRECATED);
            include $absolute;
            $content = ob_get_clean();
        } catch (\Throwable $throwable) {
            if (ob_get_level() > 0) {
                ob_end_clean();
            }

            throw new RuntimeException(
                sprintf('Legacy PHP execution failed for [%s]: %s', $file, $throwable->getMessage()),
                previous: $throwable
            );
        } finally {
            error_reporting($previousErrorReporting);
            chdir($previousDirectory ?: base_path());
            $_SERVER = $previousServer;
        }

        return response($content);
    }
}
